Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create custom array object type with additonal functions and class declaration?

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
  1. 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
  1. 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading