MikeMcl / bignumber.js

A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic
http://mikemcl.github.io/bignumber.js
MIT License
6.63k stars 743 forks source link

[Feature] Recursive operation #339

Closed c0ncentus closed 1 year ago

c0ncentus commented 1 year ago

Hi,

Context

sometimes I do math manually and cause some large code ... We have n and n+1 state ... Would be less painfull to make it via function rather have 10 variables use only for calculation.

More Data

https://en.wikipedia.org/wiki/Sequence you have many case of useful sequence. like Fibonacci https://fr.wikipedia.org/wiki/Suite_de_Fibonacci

Thats one of beauty of "Math" ...

Expected

const n1 = new BigNumber(0)

UseCase desired

n1
.suite(times)
.arguWith(3)
.arguWith(10)
.calc((n1, arg1, arg2)=>{
    // make operation here  or other things like updated UserInterface !
}
})

Signature on return

interface{
    results:BigNumber[],
    result:BigNumber
}
shuckster commented 1 year ago

Seems like your example could be straightforwardly done using regular JavaScript code:

function calc(n1, arg1, arg2) {
  return [n1.toString(), arg1, arg2];
}

const seed = BigNumber(0);
const times = 10;
const results = [];

for (let i = 0 ; i < times ; i++) {
  const n1 = BigNumber(seed);
  results.push(calc(n1, 3, 10));
}

console.log(results);

Or, if you really want that API:

class Suite {
  constructor(data) {
    this.data = data;
    this.iterations = 0;
    this.args = [];
  }

  suite(iterations) {
    this.iterations = iterations;
    return this;
  }

  arguWith(arg) {
    this.args.push(arg);
    return this;
  }

  calc(fn) {
    let result;
    const results = [];
    for (let i = 0; i < this.iterations; i++) {
      result = fn(this.data, ...this.args);
      results.push(result)
    }
    return { results, result };
  }
}

// Usage:

import BigNumber from "bignumber.js";

const n1 = BigNumber(0);

const output = new Suite(n1)
  .suite(10)
  .arguWith(3)
  .arguWith(10)
  .calc((n1, arg1, arg2) => {
    return [n1.toString(), arg1, arg2];
  });

console.log("output", output);
c0ncentus commented 1 year ago

Ok thanks 👍 .

I should do internally then :)