index.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict';
  2. var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
  3. , length = 64
  4. , map = {}
  5. , seed = 0
  6. , i = 0
  7. , prev;
  8. /**
  9. * Return a string representing the specified number.
  10. *
  11. * @param {Number} num The number to convert.
  12. * @returns {String} The string representation of the number.
  13. * @api public
  14. */
  15. function encode(num) {
  16. var encoded = '';
  17. do {
  18. encoded = alphabet[num % length] + encoded;
  19. num = Math.floor(num / length);
  20. } while (num > 0);
  21. return encoded;
  22. }
  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. var decoded = 0;
  32. for (i = 0; i < str.length; i++) {
  33. decoded = decoded * length + map[str.charAt(i)];
  34. }
  35. return decoded;
  36. }
  37. /**
  38. * Yeast: A tiny growing id generator.
  39. *
  40. * @returns {String} A unique id.
  41. * @api public
  42. */
  43. function yeast() {
  44. var now = encode(+new Date());
  45. if (now !== prev) return seed = 0, prev = now;
  46. return now +'.'+ encode(seed++);
  47. }
  48. //
  49. // Map each character to its index.
  50. //
  51. for (; i < length; i++) map[alphabet[i]] = i;
  52. //
  53. // Expose the `yeast`, `encode` and `decode` functions.
  54. //
  55. yeast.encode = encode;
  56. yeast.decode = decode;
  57. module.exports = yeast;