yeast.js 1.3 KB

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