Ho scritto questo listato in JavaScript ES5 e preferirei non utilizzare le funzionalità moderne di ES6. Vorrei un’analisi di questo listato in lingua italiana, con particolare attenzione ai seguenti punti
:
Ridondanza di codice o controlli logici: Identificare eventuali ripetizioni inutili o controlli logici superflui.
Ottimizzazioni: Suggerire miglioramenti per rendere il codice più efficiente.
Compattazioni: Proporre modi per rendere il codice più conciso.
Ricerca di maggiore efficienza e velocità di esecuzione: Consigli su come migliorare le prestazioni del codice.
Per ogni punto da 1 a 4, apprezzerei suggerimenti specifici indicando il PRIMA, cioe' il codice orginale e il DOPO, con le modifiche da te proposte. var CONFIG = {
ORDER_SIDE: 'BID',
SIZE: 1,
MAX_OPERATIONS: 3,
LEVELS: { BID: 6, ASK: 6 },
SECONDS: 5,
TICK: 1,
MONITORING_MODE: 'MONITORA_yourlevel'
};
var separator = "---------------------------------------------------\r\n";
var lastBidPrice, lastBidQuantity, lastAskPrice, lastAskQuantity;
var BookStateManager = (function() {
var cachedBookState = null;
var UserContext = {};
return {
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 = ['BID', 'ASK'];
for (var i = 0; i < sides.length; i++) {
if (this.isSideChanged(sides[i], 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 = ['BID', '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;
}
};
function collectBookLogParts(book) {
var logParts = ["BID:\n"];
addLevels(logParts, 'BID', book);
logParts.push(separator, "ASK:\n");
addLevels(logParts, 'ASK', book);
var tick = calculateTick(book.BID.Prices, book.ASK.Prices);
return logParts;
}
function logFullBook() {
var book = UserContext.book;
var logParts = collectBookLogParts(book);
logger.log('message', { message: logParts.join('') }, false); // Utilizza logger invece di Log
}
function priceUpdate(side, book, status) {
var prices = UserContext.prices[side];
var targetPriceLevel = UserContext.targetPriceLevels[side];
var targetPrice = book[side].Prices[targetPriceLevel];
var oldPrice = prices.oldLevel;
if (targetPrice === oldPrice) return;
var newOrder = OrderUtils.processOrModOrder(side, ps, targetPrice);
if (!newOrder) return;
prices.current = targetPrice;
var direction = Helper.priceDirection(targetPrice, oldPrice);
var levelDifference = (direction === 1) ? (CONFIG.LEVELS[side] + 1) :
(direction === -1) ? (CONFIG.LEVELS[side] - 1) :
CONFIG.LEVELS[side];
logger.log('LevelChange', { lastLevel: levelDifference, priceLevel: targetPriceLevel }, true);
status.secondCount = 0;
status.numOperazione++;
}
function checkOps() {
var status = UserContext.status;
if (status.numOperazione < CONFIG.MAX_OPERATIONS) {
return false;
}
Inoltre, nel metodo mapSide della funzione mapBookData, viene ripetuto il controllo della presenza delle funzioni Price e Quantity per ogni lato.
DOPO:
Per eliminare la ridondanza, possiamo astrarre il confronto in una funzione dedicata e semplificare i controlli:
// Funzione astratta per confrontare i valori
function hasDifference(cached, newVal, level, type) {
return cached[type][level] !== newVal[type][level];
}
isSideChanged: function(side, newState) {
var maxLevel = CONFIG.LEVELS[side];
var cachedSide = cachedBookState.book[side];
var newSide = newState.book[side];
for (var level = 0; level <= maxLevel; level++) {
if (hasDifference(cachedSide, newSide, level, 'Prices') ||
hasDifference(cachedSide, newSide, level, 'Quantities')) {
return true;
}
}
return false;
}
2. Ottimizzazioni
PRIMA:
Nel metodo calculateTick, si utilizza Math.floor e toFixed per calcolare e formattare il tick, e viene eseguito un ciclo completo anche dopo aver trovato una differenza minima:
var tick = parseFloat((Math.floor(minDifference / MINIMUM_TICK) * MINIMUM_TICK).toFixed(DECIMAL_PLACES));
DOPO:
Possiamo ottimizzare interrompendo il ciclo non appena troviamo una differenza che soddisfa il criterio minimo e semplificare il calcolo del tick:
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 = Math.min(bidDiff, askDiff);
if (currentMin < minDifference) {
minDifference = currentMin;
if (minDifference <= MINIMUM_TICK) break;
}
}
if (minDifference === Infinity || minDifference === 0) {
logger.log('message', { message: 'Tick calcolato: 0' });
return 0;
}
var tick = Math.floor(minDifference / MINIMUM_TICK) * MINIMUM_TICK;
tick = parseFloat(tick.toFixed(DECIMAL_PLACES));
logger.log('message', { message: 'Tick calcolato: ' + tick });
return tick;
}
3. Compattazioni
PRIMA:
Nel metodo createBookState, i cicli annidati per i lati e i tipi rendono il codice verbose:
createBookState: function(book) {
var sides = ['BID', '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;
},
DOPO:
Utilizzando una singola iterazione con combinazioni di lati e tipi, possiamo rendere il codice più conciso:
createBookState: function(book) {
var state = { book: book };
['BID', 'ASK'].forEach(function(side) {
['Price', 'Quantity'].forEach(function(type) {
var key = side.toLowerCase() + type;
state[key] = this.getData(book, side, CONFIG.LEVELS[side], type);
}, this);
}, this);
return state;
},
4. Ricerca di maggiore efficienza e velocità di esecuzione
PRIMA:
La funzione manageCycle chiama mapBookData e priceUpdate senza verificare se i dati sono effettivamente cambiati, potenzialmente causando operazioni non necessarie.
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:
Implementando un controllo per verificare se lo stato del libro è effettivamente cambiato prima di procedere con gli aggiornamenti, possiamo evitare operazioni inutili:
function manageCycle() {
var status = UserContext.status;
if (checkOps() || status.secondCount < CONFIG.SECONDS) return;
var bookData = Book(ps);
var mappedBook = mapBookData(bookData);
var previousBook = UserContext.book;
// Confronto semplice per vedere se il libro è cambiato
if (JSON.stringify(mappedBook) === JSON.stringify(previousBook)) return;
UserContext.book = mappedBook;
priceUpdate(CONFIG.ORDER_SIDE, mappedBook, status);
status.secondCount = 0;
}
Nota: Per migliorare ulteriormente l'efficienza, si potrebbe sostituire JSON.stringify con una funzione di confronto più performante se i dati sono grandi.
Altri Suggerimenti Generali
Caching delle Lunghezze dei Cicli: In alcuni cicli for, il valore length viene calcolato ad ogni iterazione. È più efficiente memorizzarlo una volta prima del ciclo.
PRIMA:
for (var i = 0; i < sides.length; i++) { /* ... */ }
DOPO:
for (var i = 0, len = sides.length; i < len; i++) { /* ... */ }
Evita Ripetizioni nelle Stringhe: Definire stringhe ripetitive come costanti può ridurre il rischio di errori e migliorare la leggibilità.
PRIMA:
var sides = ['BID', 'ASK'];
DOPO:
var SIDES = ['BID', 'ASK'];
Conclusioni
Applicando queste ottimizzazioni, riduzioni di ridondanza e compattazioni, il tuo codice diventerà più efficiente, mantenibile e performante senza dover ricorrere alle funzionalità moderne di ES6. Ricorda sempre di testare accuratamente ogni modifica per garantire che il comportamento del programma rimanga corretto.