8bc14ea7af0648e0554792b045449123cfac340ec6df668b62d8474e73b505b00838098bb9cd195ecfb40f3f291b41e40f215e5a7663899bd772fd2fddfd63 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /**
  2. * Copyright (c) 2017 ESHA Research
  3. * Dual licensed under the MIT and GPL licenses:
  4. * http://www.opensource.org/licenses/mit-license.php
  5. * http://www.gnu.org/licenses/gpl.html
  6. *
  7. * Adds shortcut for safely applying all available Array functions to stored values. If there is no
  8. * value, the functions will act as if upon an empty one. If there is a non, array value, it is put
  9. * into an array before the function is applied. If the function results in an empty array, the
  10. * key/value is removed from the storage, otherwise the array is restored.
  11. *
  12. * store.push('array', 'a', 1, true);// == store.set('array', (store.get('array')||[]).push('a', 1, true]));
  13. * store.indexOf('array', true);// === store.get('array').indexOf(true)
  14. *
  15. * This will add all functions of Array.prototype that are specific to the Array interface and have no
  16. * conflict with existing store functions.
  17. *
  18. * Status: BETA - useful, but adds more functions than reasonable
  19. */
  20. ;(function(_, Array) {
  21. // expose internals on the underscore to allow extensibility
  22. _.array = function(fnName, key, args) {
  23. var value = this.get(key, []),
  24. array = Array.isArray(value) ? value : [value],
  25. ret = array[fnName].apply(array, args);
  26. if (array.length > 0) {
  27. this.set(key, array.length > 1 ? array : array[0]);
  28. } else {
  29. this.remove(key);
  30. }
  31. return ret;
  32. };
  33. _.arrayFn = function(fnName) {
  34. return function(key) {
  35. return this.array(fnName, key,
  36. arguments.length > 1 ? Array.prototype.slice.call(arguments, 1) : null);
  37. };
  38. };
  39. // add function(s) to the store interface
  40. _.fn('array', _.array);
  41. Object.getOwnPropertyNames(Array.prototype).forEach(function(name) {
  42. // add Array interface functions w/o existing conflicts
  43. if (typeof Array.prototype[name] === "function") {
  44. if (!(name in _.storeAPI)) {
  45. _.fn(name, _.array[name] = _.arrayFn(name));
  46. }
  47. }
  48. });
  49. })(window.store._, window.Array);