yeast.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // imported from https://github.com/unshiftio/yeast
  2. "use strict";
  3. Object.defineProperty(exports, "__esModule", { value: true });
  4. exports.yeast = exports.decode = exports.encode = void 0;
  5. const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""), length = 64, map = {};
  6. let seed = 0, i = 0, prev;
  7. /**
  8. * Return a string representing the specified number.
  9. *
  10. * @param {Number} num The number to convert.
  11. * @returns {String} The string representation of the number.
  12. * @api public
  13. */
  14. function encode(num) {
  15. let encoded = "";
  16. do {
  17. encoded = alphabet[num % length] + encoded;
  18. num = Math.floor(num / length);
  19. } while (num > 0);
  20. return encoded;
  21. }
  22. exports.encode = encode;
  23. /**
  24. * Return the integer value specified by the given string.
  25. *
  26. * @param {String} str The string to convert.
  27. * @returns {Number} The integer value represented by the string.
  28. * @api public
  29. */
  30. function decode(str) {
  31. let decoded = 0;
  32. for (i = 0; i < str.length; i++) {
  33. decoded = decoded * length + map[str.charAt(i)];
  34. }
  35. return decoded;
  36. }
  37. exports.decode = decode;
  38. /**
  39. * Yeast: A tiny growing id generator.
  40. *
  41. * @returns {String} A unique id.
  42. * @api public
  43. */
  44. function yeast() {
  45. const now = encode(+new Date());
  46. if (now !== prev)
  47. return (seed = 0), (prev = now);
  48. return now + "." + encode(seed++);
  49. }
  50. exports.yeast = yeast;
  51. //
  52. // Map each character to its index.
  53. //
  54. for (; i < length; i++)
  55. map[alphabet[i]] = i;