Skip to content

Instantly share code, notes, and snippets.

@jsdevel
Last active August 29, 2015 14:03
Show Gist options
  • Save jsdevel/a2c1a51103609e538db6 to your computer and use it in GitHub Desktop.
Save jsdevel/a2c1a51103609e538db6 to your computer and use it in GitHub Desktop.
An attempt at creating an array in javascript without using Array.
var equal = require('assert').equal;
var instance = this;
var lengthFacade = 0;
this.push = function(value){
this[getLength()] = value;
};
Object.defineProperty(this, 'length', {
get: getLength,
set: setLength
});
function getLength(){
var highestProp = getHighestProp();
return typeof highestProp === 'number' && highestProp >= lengthFacade ? highestProp + 1 : lengthFacade;
}
function setLength(amount){
var length = getLength();
var starting = amount > length ? amount : length;
forNumericProps(function(prop){
if(amount <= prop)delete instance[prop];
});
lengthFacade = amount;
}
function getHighestProp(){
var highest;
forNumericProps(function(prop){
if(!highest || prop > highest)highest = prop;
});
return highest;
}
function forNumericProps(cb){
var prop;
for(prop in instance){
if(/^[0-9]+$/.test(prop))cb(parseInt(prop));
}
}
}
var a = new MyArray();
equal(a.length, 0);
a.push(5);
equal(a[0], 5);
equal(a.length, 1);
a.length = 0;
equal(a.length, 0);
a[23452345] = 5;
equal(a[23452345], 5);
equal(a.length, 23452346);
a.length = 3;
equal(a.length, 3);
a[2] = 5;
equal(a[2], 5);
delete a[2];
equal(a.length, 3);
console.log('All passed!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment