plantain-00 / expression-engine

An expression tokenizer, parser and evaluator.
MIT License
8 stars 1 forks source link

expression-engine

An expression tokenizer, parser and evaluator.

Dependency Status devDependency Status Build Status: Windows Github CI npm version Downloads gzip size type-coverage

install

yarn add expression-engine

usage

import { tokenizeExpression, parseExpression, evaluateExpression, printExpression } from "expression-engine";

const tokens = tokenizeExpression('a + b')
const ast = parseExpression(tokens)
const result = evaluateExpression(ast, { a: 1, b: 2 })
const expression = printExpression(ast)

// <script src="https://github.com/plantain-00/expression-engine/raw/master/node_modules/expression-engine/expression-engine.min.js"></script>

supported expression features(ordered by priority from high to low)

custom data

import { tokenizeExpression, parseExpression, evaluateExpression, CustomData } from 'expression-engine'

class HighlightText implements CustomData {
  constructor(public text: string, public highlight: number[]) { }

  add(right: string | HighlightText) {
    if (typeof right === 'string') {
      return new HighlightText(this.text + right, this.highlight)
    }
    const highlight = [...this.highlight]
    if (right.highlight.length > 0) {
      const [first, ...remain] = right.highlight
      highlight.push(first + this.text.length - highlight.reduce((p, c) => p + c, 0), ...remain)
    }
    return new HighlightText(this.text + right.text, highlight)
  }

  added(left: string) {
    if (this.highlight.length > 0) {
      const [first, ...remain] = this.highlight
      return new HighlightText(left + this.text, [first + left.length, ...remain])
    }
    return new HighlightText(left + this.text, this.highlight)
  }

  equal(value: string | HighlightText) {
    const text = typeof value === 'string' ? value : value.text
    const highlight = typeof value === 'string' ? [] : value.highlight || []
    if (text !== this.text) {
      return false
    }
    if (this.highlight.length !== highlight.length) {
      return false
    }
    for (let i = 0; i < highlight.length; i++) {
      if (highlight[i] !== this.highlight[i]) {
        return false
      }
    }
    return true
  }
}

const tokens = tokenizeExpression('a + b')
const ast = parseExpression(tokens)
const result = evaluateExpression(
  ast,
  {
    a: new HighlightText('aaa', [1, 1]),
    b: new HighlightText('bbb', [1, 1])
  },
  undefined,
  [HighlightText]
)
// HighlightText { text: 'aaabbb', highlight: [ 1, 1, 2, 1 ] }