0

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.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
alessandro308
  • 1,912
  • 2
  • 15
  • 27
  • If your getter returns something to which you can attach a property, of course. And you have to implement the property correctly. You've added a function, so you'd have to call it as such (`console.log(obj.latest.test());`) – Heretic Monkey Jul 18 '22 at 12:35
  • The question is, what are you trying to accomplish? As [@Quentin notes in their answer](https://stackoverflow.com/a/73022392/215552), you're returning a primitive value, so there isn't much use in adding a property to it. Also, adding properties after you've already gotten the value (rather than to the type of value returned) means those properties are only attached to the returned instance. The more context you can give us, the better answers we can provide. – Heretic Monkey Jul 18 '22 at 12:50
  • Updated with some more context – alessandro308 Jul 18 '22 at 12:57
  • The problem is that calling `obj.items` calls the getter. Once the getter returns, then it calls `withId(id)`, so you haven't saved yourself the compute time. You're better off with `object.itemsWithId(id)` and `object.items`, although I'm a proponent of putting anything that takes that much effort behind a method call, so `object.getItems()` and `object.getItemsWithId(id)` or just `object.getItems(id)`. – Heretic Monkey Jul 18 '22 at 13:03
  • I agree with you. Unfortunately the getter is already there, that was my last chance to create a more ergonomic API but I think I'll go with a getItemsWithId method as you proposed. – alessandro308 Jul 18 '22 at 13:19

1 Answers1

0

obj.latest is going to be the result of this.log[this.log.length - 1] which is going to be 'c'.

Since 'c' is a primitive, you can't (usefully) assign properties to it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335