purescript-contrib/purescript-js-bigints

fromStringAs

Closed this issue · 4 comments

I made an implementation, then when i got to the testing part i saw that fromString supports other radix already. https://github.com/purescript-contrib/purescript-js-bigints/blob/main/test/Main.purs#L81-L82

Perhaps make it more clear in the documentation. Now it says "assuming a decimal representation" which is not true in the cases when there is a prefix like 0x.

fromStringAs could still be added though, but i don't find it so necessary. Here is the implementation

export const fromStringAsImpl = function (just) {
  return function (nothing) {
    return function (radix) {

      var digits;
      if (radix < 11) {
        digits = "[0-" + (radix - 1).toString() + "]";
      } else if (radix === 11) {
        digits = "[0-9a]";
      } else {
        digits = "[0-9a-" + String.fromCharCode(86 + radix) + "]";
      }
      var pattern = new RegExp("^[\\+\\-]?" + digits + "+$", "i");

      return function (s) {
        // Not yet in the standard: https://github.com/tc39/proposal-number-fromstring
        // Code converted from https://stackoverflow.com/a/55646905/1833322

        /* jshint bitwise: false */
        if (pattern.test(s)) {
          var size = 10;
          var factor = BigInt(radix ** size);
          var r = 0n

          for (var i = 0; i < s.length; i += size) {
            var n = parseInt(s.slice(i, i + size), radix);

            // check for NaN
            if ((n | 0) !== n) {
              return nothing;
            }

            r = r * factor + BigInt(n);
          }

          return just(r);
        } else {
          return nothing;
        }
      };
    };
  };
};

Personally I have never needed it, but if you want to add it I don't see a reason why not.

Ok since i already wrote it and i also don't why not i will submit the PR for it.

Done #12 , thx @flip111