Iam struggling with creating an custom array object type with additional functions, and a class construtor:
The custom array object should have the following content:
["fruits", ["apple", "banana", "pineapple"]]; //array content: string and another array
- I would like to work on such an array with custom functions, like:
Array.prototype.returnArrayContent = function(){
this[1].forEach(element => console.log(element)); }
// But the problem in this case is I add another function to the array prototype, instead
// I would like to a new Object type which inherits all functions, property from built-in-Array-Object
- Because I read in data from JSON file I would like to create those custom array objects with a class constructor like:
new customArrayObject (["fruits", ["apple", "banana", "pineapple"]])
How could this be achieved? As Iam kind of a newbie do I need typescript for this?
>Solution :
I wouldn’t use the constructor to init the array since the native constructor just adds 1 element in the case. Having the custom array behave differently could be confusing. Just create some fill function and fill the custom array recursively. You could reuse it in the constructor also to match the native constructor:
class MyArray extends Array{
constructor(...items){
if(typeof items[0] === 'number' && items.length === 1){
return super(...items);
}
super();
this.fill(items);
}
fill(arr){
for(const item of arr){
if(Array.isArray(item)){
this.push(new MyArray().fill(item));
continue;
}
this.push(item);
}
return this;
}
}
const arr = new MyArray(...["fruits", ["apple", "banana", "pineapple"]])
console.log(JSON.stringify(arr));
const deleted = arr.splice(0,1);
console.log(deleted.constructor.name);
console.log(arr[0].constructor.name)
arr[0].fill(['some more fruits', ['mango', 'melon']]);
console.log(JSON.stringify(arr));