🐣 How to create a function with static methods
作成日: 2021/05/20
1

How to create a function with static methods

When we need to define some function and other static methods, we can define only the main function and attach the methods.

function calculator(expression) {
  return (variables) => {
    return calculator.eval(
      expression.replace(/[a-z]+/g, (key) => variables[key])
    );
  };
}

calculator.eval = (expression) => {
  return new Function(`return ${expression};`)();
};

const myEquation = calculator("x + y");

document.body.innerHTML = `
  <div>
    <div>Direct result <strong>123 + 456</strong>: ${calculator.eval(
      "123 + 456"
    )}</div>
    <div>Calculate equation <strong>x + y</strong> with ({ x: 123, y: 456 }): ${myEquation(
      {
        x: 123,
        y: 456
      }
    )}</div>
  </div>
`;

Edit calculator


Algorithms and mathematics merge with artificial intelligence in a heightened zen state, to make way for the dragon.