Skip to content

Instantly share code, notes, and snippets.

@harbirchahal
Last active February 26, 2020 18:19
Show Gist options
  • Save harbirchahal/4cf04d454cb8d25745f2787568d2f59b to your computer and use it in GitHub Desktop.
Save harbirchahal/4cf04d454cb8d25745f2787568d2f59b to your computer and use it in GitHub Desktop.
Naive native array implementation in JavaScript
/**
* 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