1.1.3 • Published 5 years ago

dux-formula v1.1.3

Weekly downloads
5
License
GPL
Repository
-
Last release
5 years ago

dux-formula

  • 介绍 纯js编写公式计算引擎,体积仅13k 支持判断语句、支持自定义函数 例如 if(a>0){b+c}

quick start

    1. 安装
 npm install dux-formula --save
    1. 在代码中使用
    
    
    // 自定义取值对象
    export default class FormulaValue {
    constructor() {
        this.reg = new RegExp('^-?([0-9]+|[0-9]{1,3}(\\,[0-9]{3})*)(\\.[0-9]{1,6})?$')
    }
    static getInstance() {
        if (!FormulaValue.instance) {
            FormulaValue.instance = new FormulaValue()
        }
        return FormulaValue.instance
    }
    compute(value, context) {
        let v = value.toLowerCase()
        if (v === 'true') {
            return true
        }
        if (v === 'false') {
            return false
        }
        if (v === 'null') {
            return null
        }
        if (value.indexOf('\'') === 0) {
            return value.substring(1, value.length - 1)
        }
        if (this.reg.test(value)) {
            if (value.indexOf('.') === -1) {
                return parseInt(value)
            } else {
                return parseFloat(value)
            }
        }
    }
}
    import FormulaEngine from 'dux-formula'
    import FormulaValue from './FormulaValue'
    const formulaEngine = new FormulaEngine()
    formulaEngine.setComputeValue(FormulaValue.getInstance()) // 设置取值对象
    const context = {A:2,B:3} // 环境变量
    const formula = 'if(A>0){(b+2)*3}' // 表达式 
    console.log(formulaEngine.execute(formula, context)) // 输出:15
    1. 自定义函数
/**
 *  函数模板
 */
export default class FuncSum {
    // 关键字 全局唯一
    getKey () {
        return 'sum'
    }
    // 语法
    getGrammar () {
        return 'sum(A1,...)'
    }
    // 分组
    getGroup () {
        return 'excel' // 所在函数分组
    }
    getType () { //  类型 1: 函数
        return 1
    }
    // 描述
    getDesc () {
        return '求和 sum(A1,...)实例 =sum(A1,A19) 解释:A1和A19 '
    }
    // 变量个数
    getVariable () { // -1 表示变量个数不确定,对于确定的函数变量个数就指定具体个数
        return -1
    }
    // 计算
    compute (variables, context) {
        let sum = 0
        for (let i = 0, l = variables.length; i < l; i++) {
            sum += variables[i] // + 丢失精度演示就不做处理了
        }
        return sum
    }

}
formulaEngine.registerFunc(new FuncSum()) // 注册函数到公式引擎中
1.1.3

5 years ago

1.1.1

5 years ago

1.1.2

5 years ago

1.1.0

5 years ago

1.0.9

5 years ago

1.0.8

5 years ago

1.0.7

5 years ago

1.0.6

5 years ago

1.0.5

5 years ago

1.0.4

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.3

5 years ago

1.0.0

5 years ago