Skip to content

Instantly share code, notes, and snippets.

@rimmer333
Last active Jun 13, 2016
Embed
What would you like to do?
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)
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
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