Last active
February 26, 2020 18:19
-
-
Save harbirchahal/4cf04d454cb8d25745f2787568d2f59b to your computer and use it in GitHub Desktop.
Naive native array implementation in JavaScript
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
/** | |
* as (typeof []) is "object" | |
*/ | |
function MyArray() { | |
const array = Object.create(MyArray.prototype); | |
Object.defineProperty(array, 'length', { | |
value: 0, | |
enumerable: false, | |
writable: true, | |
}); | |
for (const key in arguments) { | |
array.push(arguments[key]); | |
} | |
return array; | |
} | |
MyArray.prototype.push = function (item) { | |
const index = this.length; | |
this[index] = item; | |
this.length += 1; | |
return this.length; | |
} | |
MyArray.prototype.pop = function () { | |
const index = this.length - 1; | |
if (index >= 0) { | |
const item = this[index]; | |
delete this[index]; | |
this.length -= 1; | |
return item; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment