javascript - Functional programming and ES6 array subclassing -


i'm subclassing array in javascript es6 this:

export class mylist extends array {   constructor(...args) {       super(...args);   } } 

though, once use functional methods map or filter, they'll return normal javascript array again.

let mylist = new mylist(); mylist[0] = {id: 'a', name: 'tom'}; mylist[1] = {id: 'b', name: 'alice'};  let mapedlist = mylist.map((elem) => elem.name);  console.log(mylist instanceof mylist); // true console.log(mylist instanceof array); // true  console.log(mapedlist instanceof mylist); // false console.log(mapedlist instanceof array); // true 

so how can subclass javascript array without running problems?

you can implement small static function called from, can convert resulted array mylist using ecmascript 2015's reflection api.

your class this:

export class mylist extends array {   constructor(...args) {     super(...args);   }    static from(arr) {     reflect.setprototypeof(arr, new mylist);     return arr;   } } 

and then, in code, have wrap map call in from function call this:

let mapedlist = mylist.from(mylist.map((elem) => elem.name)); 

you can modify support more types of objects array.from does.


Comments

Popular posts from this blog

javascript - Google App Script ContentService downloadAsFile not working -

javascript - Function overwritting -

php - Find a regex to take part of Email -