FromBase62.mjs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * @author tcode2k16 [tcode2k16@gmail.com]
  3. * @copyright Crown Copyright 2018
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import BigNumber from "bignumber.js";
  8. import Utils from "../Utils.mjs";
  9. /**
  10. * From Base62 operation
  11. */
  12. class FromBase62 extends Operation {
  13. /**
  14. * FromBase62 constructor
  15. */
  16. constructor() {
  17. super();
  18. this.name = "From Base62";
  19. this.module = "Default";
  20. this.description = "Base62 is a notation for encoding arbitrary byte data using a restricted set of symbols that can be conveniently used by humans and processed by computers. The high number base results in shorter strings than with the decimal or hexadecimal system.";
  21. this.infoURL = "https://wikipedia.org/wiki/List_of_numeral_systems";
  22. this.inputType = "string";
  23. this.outputType = "byteArray";
  24. this.args = [
  25. {
  26. name: "Alphabet",
  27. type: "string",
  28. value: "0-9A-Za-z"
  29. }
  30. ];
  31. }
  32. /**
  33. * @param {string} input
  34. * @param {Object[]} args
  35. * @returns {byteArray}
  36. */
  37. run(input, args) {
  38. if (input.length < 1) return [];
  39. const alphabet = Utils.expandAlphRange(args[0]).join("");
  40. const BN62 = BigNumber.clone({ ALPHABET: alphabet });
  41. const re = new RegExp("[^" + alphabet.replace(/[[\]\\\-^$]/g, "\\$&") + "]", "g");
  42. input = input.replace(re, "");
  43. // Read number in using Base62 alphabet
  44. const number = new BN62(input, 62);
  45. // Copy to new BigNumber object that uses the default alphabet
  46. const normalized = new BigNumber(number);
  47. // Convert to hex and add leading 0 if required
  48. let hex = normalized.toString(16);
  49. if (hex.length % 2 !== 0) hex = "0" + hex;
  50. return Utils.convertToByteArray(hex, "Hex");
  51. }
  52. }
  53. export default FromBase62;