Bohtvaroh

Poor man's persistent map in JS

May 16th, 2014
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. define(['morearty/Util'], function (Util) {
  2.   'use strict';
  3.  
  4.   var O, getIn, update, dissoc;
  5.  
  6.   O = function (value) {
  7.     this.value = value
  8.   };
  9.  
  10.   getIn = function (obj, keys) {
  11.     return keys.reduce(function (node, key) { return node[key] }, obj)
  12.   };
  13.  
  14.   update = function (obj, keys, update) {
  15.     var keysButLast = keys.slice(0, -1);
  16.     var lastKey = keys[keys.length - 1];
  17.  
  18.     var objCopy = Util.shallowCopy(obj);
  19.  
  20.     var lastNode = keysButLast.reduce(
  21.       function (node, key) {
  22.         var subNode = Util.shallowCopy(node[key]);
  23.         node[key] = subNode;
  24.         return subNode
  25.       },
  26.       objCopy
  27.     );
  28.  
  29.     lastNode[lastKey] = update(lastNode[lastKey]);
  30.     return objCopy
  31.   };
  32.  
  33.   dissoc = function (obj, keys) {
  34.     var keysButLast = keys.slice(0, -1);
  35.     var lastKey = keys[keys.length - 1];
  36.  
  37.     return update(obj, keysButLast, function (node) { delete node[lastKey] })
  38.   };
  39.  
  40.   O.prototype = Object.freeze({
  41.  
  42.     get: function (keys) {
  43.       return getIn(this.value, keys)
  44.     },
  45.  
  46.     update: function (keys, update) {
  47.       this.value = update(this.value, keys, update)
  48.     },
  49.  
  50.     assoc: function (keys, newValue) {
  51.       this.value = update(this.value, keys, Util.constantly(newValue))
  52.     },
  53.  
  54.     dissoc: function (keys) {
  55.       dissoc(this.value, keys)
  56.     }
  57.  
  58.   });
  59.  
  60.   return {
  61.  
  62.     createO: function (value) {
  63.       return new O(value)
  64.     }
  65.  
  66.   }
  67.  
  68. });
Advertisement
Add Comment
Please, Sign In to add comment