soft-processor
v0.2.3
Published
A soft processor which can run simple calculation programs.
Downloads
11
Readme
Demo
Simple calculation
const c = {
a: 10,
b: 20
}
const p = new Processor(c)
let r:any = null
r = p.run(`
a+b;
_r/7;
.2;
`)
console.log(Object.keys(r), (r._r as Big).toNumber())
Processor supports
+
-
*
/
as mathematical operators._r
is the intermediate result during the calculation process. Special operator.
meansround
function Resultr
fromProcessor.run
is the whole context Resultr._r
is the calculation result and itstype
isBig
.
Special operator :
r = p.run(`
a-b;
:tmp;
tmp*6;
`)
console.log(Object.keys(r), (r._r as Big).toNumber(), (r.tmp as Big).toNumber())
Special operator
:
means create a new field in the context and save the intermediate result into this new field. The following calculation can use this new field.
Special operators \\
r = p.run(`
a-b;
\\abs;
`)
console.log(Object.keys(r), (r._r as Big).toNumber())
Special operator
\\
means executing aBig
function and using the intermediate result as the input parameter
Special operators !
const pf1 = new Processor(c, {
demo1: (a:number, b:number) => {
// return a Big instance will update the context._r
// else the context._r will keep unchanged
return Big(a + b)
}
})
r = pf1.run(`
!demo1,a,b;
`)
console.log(Object.keys(r), (r._r as Big).toNumber())
Processor
constructor accepts the 2nd input parameter as extension. You may provide your own extension functions here. Special operator!
means executing aBig
function and using specified context fields as input parameters
const pf2 = new Processor(c, {
demo2: (c:ContextType) => {
console.log(c)
// return a Big instance will update the context._r
// else the context._r will keep unchanged
return Big(c.a || 0).times(c.b || 0)
}
})
r = pf2.run(`
!demo2;
`)
console.log(Object.keys(r), (r._r as Big).toNumber())
If no context fields specified, the whole context will be pass into the extension function as input parameter