1

I am trying to write a TypeScript function something like this:

    import multipleActionObject from page; 
    it("should be able to do multiple operations", () => {
        multipleActionObject.chooseIndex(4).setValue(10);
    }

I would like to write a function like that instead of:

   import multipleActionObject from page; 
    it("should be able to do multiple operations", () => {
        multipleActionObject.chooseAndSetNumber(4,10);
    }

In my multipleActionObject class:

class multipleActionObject(){

        public chooseAndSetNumber(index,value){
           this.index[index].setValue(value)
        } 
 }

How do I write a helper for the first option?

JorgeAmVF
  • 1,660
  • 3
  • 21
  • 32
user3920295
  • 889
  • 2
  • 13
  • 31
  • 1
    The problem with chaining functions is that if any one fails, the whole thing fails in ways that can be very hard to find. It can also make maintenance difficult as it goes against separation of concerns and modularisation. Maybe [*How to achieve arbitrary chain on function call in javascript?*](https://stackoverflow.com/questions/26656718/how-to-achieve-arbitrary-chain-on-function-call-in-javascript). – RobG Jan 17 '19 at 00:13
  • Is this TypeScript? Is `public` a new JavaScript keyword? I can't find it... – zer00ne Jan 17 '19 at 00:22
  • Yes. Typescript. Let me edit my question. – user3920295 Jan 17 '19 at 00:38

2 Answers2

4

You can have chooseIndex assign to an index property of the instance, and then return the instance, and then have setValue look up the index that has been assigned to:

class multipleActionObject {
  constructor(arr) {
    this.arr = arr;
  }
  chooseIndex(index) {
    this._index = index;
    return this;
  }
  setValue(value) {
    if (typeof this._index !== 'number') {
      throw new Error('No index to set value of');
    }
    this.arr[this._index] = value;
    return this;
  }
}
const instance = new multipleActionObject([0, 1, 2, 3]);
instance.chooseIndex(4).setValue(10);
console.log(instance.arr[4]);

This is called "method chaining", though here it seems a bit odd to separate the item being selected from the action being performed on that object.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Use fluent interface

class multipleActionClass
{    
  chooseIndex(index) {
      this.currentIndex=index;   
      return this;
  } 

  setValue(value) {
      console.log(`set value ${value} at index ${this.currentIndex}`);
      // this.index[this.currentIndex].setValue(value) ...
      return this;
  } 
}

let multipleActionObject = new multipleActionClass();

multipleActionObject.chooseIndex(1).setValue(2);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345