adobe / json-formula

Query language for JSON documents
http://opensource.adobe.com/json-formula/
Apache License 2.0
19 stars 8 forks source link

Should we add handling for BigInt or BigNumber? #124

Closed JohnBrinkman closed 7 months ago

JohnBrinkman commented 8 months ago

Pros:

Cons

Could we implement Big Number math using existing formulas?

Some limited support seems possible. Here's a sample that registers a function to add two numbers (represented as strings) by:

register("_bigAdd", 
&(
  split(@[0], "").reverse(@) + 
  split(@[1], "").reverse(@)
).reduce(@, 
 &{
   result: accumulated.result,
   d: accumulated.carry + current
  }.{
   result: result ~ if(d>=10, d-10, d),
   carry: if (d >= 10, 1, 0)
  },
  {result: `[]`, carry: 0}
).if(carry, result ~ 1, result)
.reverse(@)
.join(@, "")
)

_bigAdd(["12345", "6789"]) => "19134"

_bigAdd(["2147483647", "97852516353"]) => "100000000000"

A brute force multiplication function could be registered by leveraging bigAdd():

register("_bigMultiply", 
&{
  a1: rept(@[0] & ",", length(@[1])).split(@, ","),
  a2: @[1].split(@, "").reverse(@)
}.zip(a1,a2)
.map(@, &rept(@[0] & ",", @[1]).split(@, ",")[?@])
.map(@, &reduce(@, &_bigAdd([accumulated, current]), "0"))
.reduce(@, &_bigAdd([accumulated, current & rept("0", index)]), "0"))

Then _bigMultiply(["12345", "6789"]) => "83810205"

JohnBrinkman commented 7 months ago

Received for information.