Certamente, ecco un'analisi dettagliata del tuo codice JavaScript ES5, focalizzata sui quattro aspetti richiesti. Per ciascun punto, fornirò esempi specifici evidenziando il codice prima (“PRIMA”) e dopo le modifiche suggerite (“DOPO”).
1. Ridondanza di codice o controlli logici
Esempio 1: Duplice gestione dello stato del libro tra BookStateManager e BookUtils
PRIMA:
var BookStateManager = (function() {
// ... codice esistente ...
})();
var BookUtils = (function() {
return {
// Funzioni che richiamano direttamente BookStateManager
hasBookStateChanged: function(newState) {
return BookStateManager.hasBookStateChanged(newState);
},
isSideChanged: function(side, newState) {
return BookStateManager.isSideChanged(side, newState);
},
createBookState: function(book) {
return BookStateManager.createBookState(book);
},
getBookState: function(book) {
return BookStateManager.getBookState(book);
}
};
})();
Problema: BookUtils funge da semplice wrapper per BookStateManager, creando una ridondanza inutile.
DOPO:
var BookUtils = (function() {
var cachedBookState = null;
return {
SIDES: { BID: 'BID', ASK: 'ASK' },
TYPES: { PRICE: 'Price', QUANTITY: 'Quantity' },
getBookState: function(book) {
var newState = this.createBookState(book);
if (this.hasBookStateChanged(newState)) {
cachedBookState = newState;
StateManager.updateLastValues(newState);
}
return cachedBookState;
},
hasBookStateChanged: function(newState) {
if (!cachedBookState) return true;
var sides = this.SIDES;
for (var sideKey in sides) {
if (sides.hasOwnProperty(sideKey)) {
if (this.isSideChanged(sides[sideKey], newState)) {
return true;
}
}
}
return false;
},
isSideChanged: function(side, newState) {
var maxLevel = CONFIG.LEVELS[side];
var cachedPrices = cachedBookState.book[side].Prices;
var cachedQuantities = cachedBookState.book[side].Quantities;
var newPrices = newState.book[side].Prices;
var newQuantities = newState.book[side].Quantities;
for (var level = 0; level <= maxLevel; level++) {
if (cachedPrices[level] !== newPrices[level] ||
cachedQuantities[level] !== newQuantities[level]) {
return true;
}
}
return false;
},
createBookState: function(book) {
var sides = [this.SIDES.BID, this.SIDES.ASK];
var types = ['Price', 'Quantity'];
var state = { book: book };
for (var i = 0; i < sides.length; i++) {
var side = sides[i];
for (var j = 0; j < types.length; j++) {
var type = types[j];
var key = side.toLowerCase() + type;
state[key] = this.getData(book, side, CONFIG.LEVELS[side], type);
}
}
return state;
},
getData: function(book, side, level, type) {
return book && book[side] && book[side][type + 's'] ? book[side][type + 's'][level] : undefined;
}
};
})();
Vantaggi:
- Elimina la necessità di due moduli separati (
BookStateManager e BookUtils), riducendo la ridondanza.
- Centralizza la gestione dello stato del libro in un unico modulo.
2. Ottimizzazioni
Esempio 2: Migliorare l'efficienza nella funzione calculateTick
PRIMA:
function calculateTick(bidPrices, askPrices) {
var MINIMUM_TICK = 0.005;
var DECIMAL_PLACES = 3;
if (!bidPrices || !askPrices || !bidPrices.length || !askPrices.length) {
logger.log('message', { message: 'Tick calcolato: 0' });
return 0;
}
var minDifference = Infinity;
var len = Math.min(bidPrices.length, askPrices.length);
for (var i = 0; i < len - 1; i++) {
minDifference = Math.min(
minDifference,
Math.abs(bidPrices[i] - bidPrices[i + 1]),
Math.abs(askPrices[i] - askPrices[i + 1])
);
}
if (minDifference === Infinity || minDifference === 0) {
logger.log('message', { message: 'Tick calcolato: 0' });
return 0;
}
var tick = parseFloat(
(Math.floor(minDifference / MINIMUM_TICK) * MINIMUM_TICK)
.toFixed(DECIMAL_PLACES)
);
logger.log('message', { message: 'Tick calcolato: ' + tick });
return tick;
}
Problema: La funzione calcola minDifference iterando su tutti i livelli anche se potrebbe trovare rapidamente una differenza minima.
DOPO:
function calculateTick(bidPrices, askPrices) {
var MINIMUM_TICK = 0.005;
var DECIMAL_PLACES = 3;
if (!bidPrices || !askPrices || bidPrices.length < 2 || askPrices.length < 2) {
logger.log('message', { message: 'Tick calcolato: 0' });
return 0;
}
var minDifference = Infinity;
var len = Math.min(bidPrices.length, askPrices.length);
for (var i = 0; i < len - 1; i++) {
var bidDiff = Math.abs(bidPrices[i] - bidPrices[i + 1]);
var askDiff = Math.abs(askPrices[i] - askPrices[i + 1]);
var currentMin = bidDiff < askDiff ? bidDiff : askDiff;
if (currentMin < minDifference) {
minDifference = currentMin;
if (minDifference <= MINIMUM_TICK) break; // Se minimo possibile, interrompi
}
}
if (minDifference === Infinity || minDifference === 0) {
logger.log('message', { message: 'Tick calcolato: 0' });
return 0;
}
var tick = parseFloat(
(Math.floor(minDifference / MINIMUM_TICK) * MINIMUM_TICK)
.toFixed(DECIMAL_PLACES)
);
logger.log('message', { message: 'Tick calcolato: ' + tick });
return tick;
}
Vantaggi:
- Riduce il numero di calcoli necessari interrompendo il ciclo quando si trova una differenza minima possibile.
- Migliora la leggibilità distinguendo chiaramente le differenze bid e ask.
3. Compattazioni
Esempio 3: Ridurre la verbosità nelle inizializzazioni delle proprietà di UserContext
PRIMA:
UserContext = {
book: originalBook,
order: { current: null },
status: { run: true, secondCount: 0, numOperazione: 0 },
prices: initializePrices({ BID: pricesBID, ASK: pricesASK }, sideLevels),
targetPriceLevels: sideLevels
};
Miglioramento: Utilizzare una funzione di inizializzazione per aggregare e ridurre il codice ripetitivo.
DOPO:
function initializeUserContext(book, pricesBID, pricesASK, sideLevels) {
return {
book: book,
order: { current: null },
status: { run: true, secondCount: 0, numOperazione: 0 },
prices: {
BID: { current: pricesBID[0], oldLevel: pricesBID[sideLevels.BID] },
ASK: { current: pricesASK[0], oldLevel: pricesASK[sideLevels.ASK] }
},
targetPriceLevels: sideLevels
};
}
// Uso della funzione
UserContext = initializeUserContext(originalBook, pricesBID, pricesASK, sideLevels);
Vantaggi:
- Maggiore compattezza e riusabilità del codice.
- Migliora la manutenzione facilitando le modifiche future.
Esempio 4: Unificazione delle funzioni addLevels per BID e ASK
PRIMA:
function addLevels(logParts, side, book) {
for (var level = 0, len = CONFIG.LEVELS[side] + 1; level < len; level++) {
logParts.push("Level " + level + ": Price = " + book[side].Prices[level] + ", Quantity = " + book[side].Quantities[level] + "\n");
}
}
function collectBookLogParts(book) {
var logParts = [separator, "BID:\n"];
addLevels(logParts, 'BID', book);
logParts.push(separator, "ASK:\n");
addLevels(logParts, 'ASK', book);
var tick = calculateTick(book.BID.Prices, book.ASK.Prices);
logParts.push(separator);
logParts.push("Tick: " + tick + "\n");
logParts.push(separator);
return logParts;
}
DOPO: (Elimina ripetizioni e rendi il codice più compatto)
function collectBookLogParts(book) {
var logParts = [separator];
['BID', 'ASK'].forEach(function(side) {
logParts.push(side + ":\n");
for (var level = 0; level <= CONFIG.LEVELS[side]; level++) {
logParts.push("Level " + level + ": Price = " + book[side].Prices[level] + ", Quantity = " + book[side].Quantities[level] + "\n");
}
logParts.push(separator);
});
var tick = calculateTick(book.BID.Prices, book.ASK.Prices);
logParts.push("Tick: " + tick + "\n", separator);
return logParts;
}
Vantaggi:
- Riduce la duplicazione del codice utilizzando cicli e metodi iterativi.
- Migliora la leggibilità aggregando le operazioni simili.
4. Miglioramento dell’efficienza e della velocità di esecuzione
Esempio 5: Ottimizzare la gestione degli eventi eliminando duplicate references
PRIMA:
var eventHandlers = {};
eventHandlers[TSEventType.Price] = function(ctx) {
var price = Val(ps, "LAST");
if (ctx.lastPrice === price) return;
logger.log('PriceChange', {
previousPrice: ctx.lastPrice,
currentPrice: price,
currentTime: Now().ToString("HH:mm:ss.ff")
});
ctx.lastPrice = price;
};
eventHandlers[TSEventType.Time] = function(ctx) {
ctx.status.secondCount++;
manageCycle();
};
Problema: Definire gli handlers in un oggetto può causare overhead se non necessario.
DOPO: (Ottimizzazione utilizzando funzioni dirette senza l'oggetto intermedio)
function onPriceEvent(ctx) {
var price = Val(ps, "LAST");
if (ctx.lastPrice === price) return;
logger.log('PriceChange', {
previousPrice: ctx.lastPrice,
currentPrice: price,
currentTime: Now().ToString("HH:mm:ss.ff")
});
ctx.lastPrice = price;
}
function onTimeEvent(ctx) {
ctx.status.secondCount++;
manageCycle();
}
function handleEvent(context, type) {
if (type === TSEventType.Price) {
onPriceEvent(context);
} else if (type === TSEventType.Time) {
onTimeEvent(context);
}
}
Vantaggi:
- Elimina la necessità di accesso tramite chiave in un oggetto, riducendo l'overhead.
- Migliora la cache locality e le performance di esecuzione.
Esempio 6: Minimizzare le accessi ripetuti a proprietà annidate
PRIMA:
function manageCycle() {
var status = UserContext.status;
if (checkOps() || status.secondCount < CONFIG.SECONDS) return;
var bookData = Book(ps);
UserContext.book = mapBookData(bookData);
priceUpdate(CONFIG.ORDER_SIDE, UserContext.book, status);
status.secondCount = 0;
}
DOPO: (Cache delle proprietà annidate per ridurre gli accessi ripetuti)
function manageCycle() {
var status = UserContext.status;
if (checkOps() || status.secondCount < CONFIG.SECONDS) return;
var bookData = Book(ps);
var mappedBook = mapBookData(bookData);
UserContext.book = mappedBook;
priceUpdate(CONFIG.ORDER_SIDE, mappedBook, status);
status.secondCount = 0;
}
Vantaggi:
- Riduce gli accessi ripetuti a
UserContext.book, migliorando leggermente le prestazioni.
- Maggiore chiarezza nel passaggio di variabili.
Ulteriori Suggerimenti Generali
Semplificazione delle Funzioni di Logging
PRIMA:
logFullBook: function() {
var book = UserContext.book;
var logParts = collectBookLogParts(book);
logger.log('message', { message: logParts.join('') }, false); // Utilizza logger invece di Log
}
DOPO: (Utilizzare funzioni inline e ridurre i passaggi intermedi)
function logFullBook() {
var book = UserContext.book;
var message = separator + "BID:\n";
['BID', 'ASK'].forEach(function(side) {
for (var level = 0; level <= CONFIG.LEVELS[side]; level++) {
message += "Level " + level + ": Price = " + book[side].Prices[level] + ", Quantity = " + book[side].Quantities[level] + "\n";
}
message += separator;
});
message += "Tick: " + calculateTick(book.BID.Prices, book.ASK.Prices) + "\n" + separator;
logger.log('message', { message: message }, false);
}
Vantaggi:
- Elimina la necessità di utilizzare array per raccogliere parti del log.
- Riduce la complessità delle funzioni di supporto.
Ottimizzare initializePrices
PRIMA:
function initializePrices(prices, levels) {
return {
BID: { current: prices.BID[0], oldLevel: prices.BID[levels.BID] },
ASK: { current: prices.ASK[0], oldLevel: prices.ASK[levels.ASK] }
};
}
DOPO: (Utilizzare alias per ridurre gli accessi ripetuti)
function initializePrices(prices, levels) {
var bidPrices = prices.BID;
var askPrices = prices.ASK;
var bidLevel = levels.BID;
var askLevel = levels.ASK;
return {
BID: { current: bidPrices[0], oldLevel: bidPrices[bidLevel] },
ASK: { current: askPrices[0], oldLevel: askPrices[askLevel] }
};
}
Vantaggi:
- Riduce gli accessi multipli a
prices.BID, prices.ASK, levels.BID, e levels.ASK.
- Aumenta leggermente l'efficienza e la leggibilità.
Conclusioni
Implementando le modifiche suggerite, potresti ottenere un codice più pulito, efficiente e facile da mantenere. La riduzione della ridondanza semplifica la struttura complessiva, mentre le ottimizzazioni e le compattazioni migliorano le prestazioni e la leggibilità. Continuare a rifattorizzare e rivedere il codice in base a questi principi ti aiuterà a mantenere un alto standard di qualità nel tuo sviluppo JavaScript ES5.