A powerful formula evaluation engine for TypeScript/JavaScript applications.
npm install sf-formula
This library provides multiple import paths to avoid dependency conflicts, especially with CodeMirror:
import { formulaEval } from 'sf-formula';
// For projects that want to avoid CodeMirror dependencies
import { formulaEval } from 'sf-formula/core';
// Direct access to TypeScript source files
import { formulaEval } from 'sf-formula/src';
// Import specific functionality
import { defaultFunctions } from 'sf-formula/functions';
import { parser } from 'sf-formula/parser';
If you're using CodeMirror in your project and experiencing conflicts, use the /core
import:
import { formulaEval } from 'sf-formula/core';
import { EditorView } from '@codemirror/view'; // Your own CodeMirror version
// This avoids duplicate CodeMirror instances
const result = formulaEval('2 + 2');
For CodeMirror language support (syntax highlighting, autocompletion), install peer dependencies:
npm install @codemirror/language @codemirror/autocomplete @lezer/common @lezer/highlight @lezer/lr
Then use:
import { languagePack } from 'sf-formula';
import { EditorView } from '@codemirror/view';
const view = new EditorView({
extensions: [languagePack()],
// ... other config
});
import { formulaEval } from 'sf-formula/core';
// Simple evaluation
const result = formulaEval('2 + 2'); // 4
// With variables
const context = { x: 10, y: 5 };
const result2 = formulaEval('x + y', context); // 15
// With nested objects
const context2 = { user: { age: 25 } };
const result3 = formulaEval('user.age > 18', context2); // true
// With functions
const result4 = formulaEval('IF(x > 0, "positive", "negative")', { x: 5 }); // "positive"
If you need CodeMirror integration, install these peer dependencies:
@codemirror/language
@codemirror/autocomplete
@lezer/common
@lezer/highlight
@lezer/lr
MIT