i create this which is my version of array but with some modifications in this array you cant change the length like with the original array
let ary = [1,2,3];
console.log(ary.length); //3
ary.length = 999;
console.log(ary.length); //999
because i use get function to get my length and use closures for saving the value of original array length
let myArray = new MyArray(1,10); //new MyArray(from,to)
console.log(myArray.length); // 10
myArray.length = 999;
console.log(myArray.length); // 10 //still 10 because .length is a get function
the code of my array is
let _getlength = {}, _inclength = {}, _declength = {};
class MyArray{
constructor(from, to)
{
this.key = Symbol('ignore this key');
//i make it a closer because i don't want any one to change the length
// by this my length become private and can be only incremented by one by "_inclength()" function or
[_getlength[this.key], _inclength[this.key], _declength[this.key]] = (
() =>
{
let length = 0;
let getLength = () =>
{
return length;
};
let inclength = () =>
{
length++;
this[length - 1] = 0;
return length;
};
let declength = () =>
{
return --length;
};
return [getLength, inclength, declength];
}
)();
if (from != null || to != null)
{
for (let num = from; num <= to; num++)
{
this.push(num);
}
}
}
push(value)
{
this[this.IncreaseLengthByOne() - 1] = value;
}
unshift(value)
{
this.addAt(0, value)
}
addAt(index, value)
{
this.IncreaseLengthByOne();
for (let i = this.length - 2; i >= index; i--)
{
this[i + 1] = this[i];
}
this[index] = value;
}
removeAt(index)
{
for (let i = index; i < this.length - 1; i++)
{
this[i] = this[i + 1];
}
this.pop();
}
pop()
{
_declength[this.key]();
delete this[this.length];
}
get length()
{
return _getlength[this.key]();
}
IncreaseLengthByOne()
{
return _inclength[this.key]();
}
forEach(callback)
{
for (let i = 0; i < this.length; i++)
{
callback(this[i], i, this);
}
}
map(callback)
{
let myArray = new MyArray();
for (let i = 0; i < this.length; i++)
{
myArray.push(callback(this[i], i, this));
}
return myArray;
}
// if you don't know what it is then go and learn what generators are! what Symbol(primitive type) is and what Symbol.iterator is then
// come back
* [Symbol.iterator]()
{
for (let i = 0; i < this.length; i++)
{
yield this[i];
}
}
}
examples:
create an array of names and add "Ali", "Hadi", "Amber" to it
let names = new MyArray();
names.push('Ali');
names.push('Hadi');
names.push('Amber');
console.log(names); // MyArray {0: "Ali", 1: "Hadi", 2: "Amber"}
modify every name by adding there last name "Nawaz" at the end Like "Ali" become "Ali Nawaz"
let fullNames = names.map(nam => nam +' Nawaz');
console.log(fullNames); //MyArray {0: "Ali Nawaz", 1: "Hadi Nawaz", 2: "Amber Nawaz"}