Last active
March 24, 2019 17:43
-
-
Save maumchaves/c0e933fee6dd9c19d4609a22b0c977f0 to your computer and use it in GitHub Desktop.
Custom implementation of Array.push() as described by Douglas Crockford in his book "JavaScript: The Good Parts". The breakdown / analysis is my own.
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
/* TL;DR: | |
* The method replicates the functionality of Array.push | |
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push | |
* Array.method("myFunction", function() {}) is just an imaginary pre-implemented function that | |
* is equivalent to Array.prototype.myFunction = function() {} | |
*/ | |
Array.method('push', function() { | |
// array.splice(start[, deleteCount[, item1[, item2[, ...]]]]) | |
// function.apply(thisArg, [argsArray]) | |
this.splice.apply( | |
this, // thisArg | |
[this.length, 0] // First to elements in argsArray, so they stand for 'start' and 'deleteCount' | |
.concat( | |
Array.prototype.slice.apply(arguments) // Create a clean array with the values we need to push out of the arguments passed to "push": item1, item2... | |
) // After the concat we will have something like [arrayLength, 0, item1, item2...] | |
); | |
// At this point, we are actually doing is: | |
// this.splice.apply(theArrayAsThis, [arrayLength, 0, item1, item2...]) | |
// which is actually: | |
// theArray.splice(arrayLength, 0, item1, item2...) | |
return this.length; // Finally we have to return the new array length, just as the native push method does | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment