Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- define(['morearty/Util'], function (Util) {
- 'use strict';
- var O, getIn, update, dissoc;
- O = function (value) {
- this.value = value
- };
- getIn = function (obj, keys) {
- return keys.reduce(function (node, key) { return node[key] }, obj)
- };
- update = function (obj, keys, update) {
- var keysButLast = keys.slice(0, -1);
- var lastKey = keys[keys.length - 1];
- var objCopy = Util.shallowCopy(obj);
- var lastNode = keysButLast.reduce(
- function (node, key) {
- var subNode = Util.shallowCopy(node[key]);
- node[key] = subNode;
- return subNode
- },
- objCopy
- );
- lastNode[lastKey] = update(lastNode[lastKey]);
- return objCopy
- };
- dissoc = function (obj, keys) {
- var keysButLast = keys.slice(0, -1);
- var lastKey = keys[keys.length - 1];
- return update(obj, keysButLast, function (node) { delete node[lastKey] })
- };
- O.prototype = Object.freeze({
- get: function (keys) {
- return getIn(this.value, keys)
- },
- update: function (keys, update) {
- this.value = update(this.value, keys, update)
- },
- assoc: function (keys, newValue) {
- this.value = update(this.value, keys, Util.constantly(newValue))
- },
- dissoc: function (keys) {
- dissoc(this.value, keys)
- }
- });
- return {
- createO: function (value) {
- return new O(value)
- }
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment