Reputation: 55
I'm tying to model a custom data type with JS and wondering if there's a more elegant way of doing this.
Ultimately I'd like the data type to essentially behave like an array but with an extended set of methods to meet my specific application and can be seen in the Links class below.
class Node {
constructor() {
this.links = new Links();
}
}
class Links {
constructor(node) {
this.data = [];
}
initialize() {
let initArray = [];
let maximumIncrement = hypotheticalNodeArray.length;
for (let i = 0; i < maximumIncrement ; i++) {
array[i] = 0;
}
this.data = array;
}
// More Methods Here
}
Essentially my issue is if I were to attempt to access the links data with [ node.links ] the entire object would be returned where as I'd love it just to return the data property as if the data had been accessed with [ node.links.data ].
I'm aware that just having to add that extra property isn't the end of the world, but I'd really like it if the object were to behave like an array except with an extended set of methods.
I'm not sure if this possible and I appreciate it's rather pedantic, however it would really clean the code I'm working on up.
Upvotes: 1
Views: 67
Reputation: 27245
You could define a getter that returns the internal array:
class Node {
constructor() {
// renamed “_links” because we want the getter named “links”
this._links = new Links();
}
get links () {
return this._links.data;
}
}
const node = new Node();
node.links.map( ... ) // node.links is node._links.data
Upvotes: 1