Skip to content

Instantly share code, notes, and snippets.

@A1rPun
Last active November 26, 2015 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save A1rPun/189c7a7d9b46f013bc6b to your computer and use it in GitHub Desktop.
Save A1rPun/189c7a7d9b46f013bc6b to your computer and use it in GitHub Desktop.
Create an observed array
/*
* @function createObservedArray
* @params function observer A callback function returning the name of the used Array function.
* @returns Array The observed array
* @note This is just a simple way to observe an array, do not use in production ;)
*/
function createObservedArray(observer) {
var array = [],
methods = ['pop', 'push', 'shift', 'unshift', 'slice', 'splice', 'reduce'];
for (var i = methods.length; i--;) {
var fn = methods[i];
array[fn] = (function (name) {
return function () {
var r = Array.prototype[name].apply(array, arguments);
observer.call(array, name);
return r;
}
}(fn));
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment