Last active
June 13, 2016 09:07
-
-
Save genee19/1e12505ce9950bb5069b646e05383ba3 to your computer and use it in GitHub Desktop.
Non-mutating actors for Array and Object in CoffeeScript / JavaScript (like immutable, but not completely, results are still usual Array or Object that you can mutate)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NMA = | |
Array: | |
push: (array, items...) -> | |
array.concat(items) | |
set: (array, index, item) -> | |
array[...index].concat([item]).concat(array[index+1...]) | |
del: (array, index) -> | |
(item for item, i in array when i isnt index) | |
Object: | |
set: (obj, key, value) -> | |
result = (NMA.Object.del(obj, key)) | |
result[key] = value | |
result | |
del: (obj, key) -> | |
result = {} | |
result[k] = v for own k, v of obj when k isnt key | |
result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var NMA, | |
slice = [].slice, | |
hasProp = {}.hasOwnProperty; | |
NMA = { | |
Array: { | |
push: function() { | |
var array, items; | |
array = arguments[0], items = 2 <= arguments.length ? slice.call(arguments, 1) : []; | |
return array.concat(items); | |
}, | |
set: function(array, index, item) { | |
return array.slice(0, index).concat([item]).concat(array.slice(index + 1)); | |
}, | |
del: function(array, index) { | |
var i, item, j, len, results; | |
results = []; | |
for (i = j = 0, len = array.length; j < len; i = ++j) { | |
item = array[i]; | |
if (i !== index) { | |
results.push(item); | |
} | |
} | |
return results; | |
} | |
}, | |
Object: { | |
set: function(obj, key, value) { | |
var result; | |
result = NMA.Object.del(obj, key); | |
result[key] = value; | |
return result; | |
}, | |
del: function(obj, key) { | |
var k, result, v; | |
result = {}; | |
for (k in obj) { | |
if (!hasProp.call(obj, k)) continue; | |
v = obj[k]; | |
if (k !== key) { | |
result[k] = v; | |
} | |
} | |
return result; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment