Add a logging to store info about users actions JavaScript

Viewed 62

I create a function for this. Maybe exists a better solutions for this?

function writeLog(operationIdentifier, prevResult, operationNumber, newResult) {
const logEntry = {
    operation: operationIdentifier,
    prevResult: prevResult,
    number: operationNumber,
    result: newResult,
};
logEntries.push(logEntry);
console.log(logEntries);

From this:

function add() {
    const enteredNumber = getUserNumberInput();
    const initialResult = currentResult;
    currentResult += enteredNumber;
    createAndWriteOutput('+', initialResult, enteredNumber);
    writeLog('ADD', initialResult, enteredNumber, currentResult);
}
1 Answers

You can try to use Proxy for logging

const increment = a => a + 1;

const proxy = new Proxy(increment, {
  apply(target, thisArg, args) {
    console.log(`Incrementing the value "${args[0]}"`);
    const result = target(...args);
    console.log(`Result: "${result}"`);
    return result;
  },
});

increment(5); 
/* nothing logs here */

proxy(5);
/* Incrementing the value "5".
Result: "6" */
Related