How to execute formulajs formulas dynamically

103 Views Asked by At

I want to execute the formulajs formulas dynamically in react typescript application. I added my code below. can anyone help me to rectify this problem. SUM([1, 2, 3] coming as parameter I want to execute.

import React, { useState } from "react";
import * as formulajs from "@formulajs/formulajs"; // Import the formulajs library
import { object } from "prop-types";
function App() {
  const [result, setResult] = useState(0);

  const handleCalculate = () => {
    // Replace this formula with the one you want to calculate
    var test="SUM([1, 2, 3]";
    let result = formulajs.test;
    try {
      setResult(result);
      console.log(Object.keys(formulajs));
    } catch (error) {}
  };

  return (
    <div>
      <h1>Formula Calculator</h1>
      <button onClick={handleCalculate}>Calculate</button>
      {result && <p>Result: {result}</p>}
    </div>
  );
}

export default App;

Another one doubt is i have clax.js. but it's a JavaScript file how to import JS file or how to convert this repo into npm package.

I tried below code but its not working.

import React, { useState } from "react";
import * as formulajs from "@formulajs/formulajs"; // Import the formulajs library
import { object } from "prop-types";
function App() {
  const [result, setResult] = useState(0);

  const handleCalculate = () => {
    // Replace this formula with the one you want to calculate
    var test="SUM([1, 2, 3]";
    let result = formulajs.test;
    try {
      setResult(result);
      console.log(Object.keys(formulajs));
    } catch (error) {}
  };

  return (
    <div>
      <h1>Formula Calculator</h1>
      <button onClick={handleCalculate}>Calculate</button>
      {result && <p>Result: {result}</p>}
    </div>
  );
}

export default App;

1

There are 1 best solutions below

0
On

Have you tried using the apply method?

import * as formulajs from '@formulajs/formulajs';

const args1 = [1, 2, 3, 4, 5];
 
// using .apply in a class
console.log('SUM:', formulajs.SUM.apply(this, args1));

// using .apply in a function
console.log('SUM:', formulajs.SUM.apply(null, args1));

//. using .apply with the spread operator
console.log('SUM:', formulajs.SUM.apply(...args1));

I hope this helps.