Is there a way to add a property on a getter function?
Ideally, the code I want to write is:
const obj = {
log: ['a', 'b', 'c'],
get latest() {
return this.log[this.log.length - 1];
}
};
obj.latest.test = () => 123;
console.log(obj.latest);
// expected output: "c"
console.log(obj.latest.test())
// expect output: 123
My actual desire is this: since my getter perform a pretty huge computation, for instance:
const obj = {
otherproperties: ['a', 'b', 'c'],
get items() {
// VERY HUGE COMPUTATION...
return [item0, item1, item2, item3]
}
};
and sometimes I need only an element from the result, I want to write something:
obj.items.withId = (id) => {
// Don't run the entire huge computation but..
return computeOnlyId(id);
}
so to be able to write obj.items
if I want all the values, or obk.items.withId(1)
if I want only a specific item.
Probably, editing this question, I already understood that this is impossible since items
it's a getter but I leave to you the keyboards for the answers.
What I would like to avoid is to have to write obj.items.all()
to get all of them and obj.items.withId(id)
to get only once.