layerCache.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. var has = require('has');
  3. var uniq = require('uniqs');
  4. function LayerCache (opts) {
  5. if (!(this instanceof LayerCache)) {
  6. return new LayerCache(opts);
  7. }
  8. this._values = [];
  9. this._startIndex = opts.startIndex || 1;
  10. }
  11. function ascending (a, b) {
  12. return a - b;
  13. }
  14. function reduceValues (list, value, index) {
  15. list[value] = index + this._startIndex;
  16. return list;
  17. }
  18. LayerCache.prototype._findValue = function (value) {
  19. if (has(this._values, value)) {
  20. return this._values[value];
  21. }
  22. return false;
  23. };
  24. LayerCache.prototype.optimizeValues = function () {
  25. this._values = uniq(this._values).sort(ascending).reduce(reduceValues.bind(this), {});
  26. };
  27. LayerCache.prototype.addValue = function (value) {
  28. var parsedValue = parseInt(value, 10);
  29. // pass only valid values
  30. if (!parsedValue || parsedValue < 0) {
  31. return;
  32. }
  33. this._values.push(parsedValue);
  34. };
  35. LayerCache.prototype.getValue = function (value) {
  36. var parsedValue = parseInt(value, 10);
  37. return this._findValue(parsedValue) || value;
  38. };
  39. module.exports = LayerCache;