index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. 'use strict';
  2. var hat = require('hat');
  3. /**
  4. * Create a new id generator / cache instance.
  5. *
  6. * You may optionally provide a seed that is used internally.
  7. *
  8. * @param {Seed} seed
  9. */
  10. function Ids(seed) {
  11. if (!(this instanceof Ids)) {
  12. return new Ids(seed);
  13. }
  14. seed = seed || [ 128, 36, 1 ];
  15. this._seed = seed.length ? hat.rack(seed[0], seed[1], seed[2]) : seed;
  16. }
  17. module.exports = Ids;
  18. /**
  19. * Generate a next id.
  20. *
  21. * @param {Object} [element] element to bind the id to
  22. *
  23. * @return {String} id
  24. */
  25. Ids.prototype.next = function(element) {
  26. return this._seed(element || true);
  27. };
  28. /**
  29. * Generate a next id with a given prefix.
  30. *
  31. * @param {Object} [element] element to bind the id to
  32. *
  33. * @return {String} id
  34. */
  35. Ids.prototype.nextPrefixed = function(prefix, element) {
  36. var id;
  37. do {
  38. id = prefix + this.next(true);
  39. } while (this.assigned(id));
  40. // claim {prefix}{random}
  41. this.claim(id, element);
  42. // return
  43. return id;
  44. };
  45. /**
  46. * Manually claim an existing id.
  47. *
  48. * @param {String} id
  49. * @param {String} [element] element the id is claimed by
  50. */
  51. Ids.prototype.claim = function(id, element) {
  52. this._seed.set(id, element || true);
  53. };
  54. /**
  55. * Returns true if the given id has already been assigned.
  56. *
  57. * @param {String} id
  58. * @return {Boolean}
  59. */
  60. Ids.prototype.assigned = function(id) {
  61. return this._seed.get(id) || false;
  62. };
  63. /**
  64. * Unclaim an id.
  65. *
  66. * @param {String} id the id to unclaim
  67. */
  68. Ids.prototype.unclaim = function(id) {
  69. delete this._seed.hats[id];
  70. };
  71. /**
  72. * Clear all claimed ids.
  73. */
  74. Ids.prototype.clear = function() {
  75. var hats = this._seed.hats,
  76. id;
  77. for (id in hats) {
  78. this.unclaim(id);
  79. }
  80. };