index.js 697 B

123456789101112131415161718192021222324252627282930313233
  1. var ensureTwoPower = function(n) {
  2. if (n && !(n & (n - 1))) return n;
  3. var p = 1;
  4. while (p < n) p <<= 1;
  5. return p;
  6. };
  7. var Cyclist = function(size) {
  8. if (!(this instanceof Cyclist)) return new Cyclist(size);
  9. size = ensureTwoPower(size);
  10. this.mask = size-1;
  11. this.size = size;
  12. this.values = new Array(size);
  13. };
  14. Cyclist.prototype.put = function(index, val) {
  15. var pos = index & this.mask;
  16. this.values[pos] = val;
  17. return pos;
  18. };
  19. Cyclist.prototype.get = function(index) {
  20. return this.values[index & this.mask];
  21. };
  22. Cyclist.prototype.del = function(index) {
  23. var pos = index & this.mask;
  24. var val = this.values[pos];
  25. this.values[pos] = undefined;
  26. return val;
  27. };
  28. module.exports = Cyclist;