Last active
November 26, 2015 15:06
-
-
Save A1rPun/189c7a7d9b46f013bc6b to your computer and use it in GitHub Desktop.
Create an observed array
This file contains 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
/* | |
* @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