2

I want to change my code to execute chaining. this is my code:

let stepCount = {
    step: 0,
    up() {
        this.step++;
    },
    down() {
        this.step--;
    },
    showStep: function () {
       return this.step;
    }
};

How should I change it? I want to execute this code to get answer

stepCount.up().up().down().up();

2 Answers 2

2

you just need to return the current object from each function like this

let stepCount = {
  step: 0,
  up() {
    this.step++;
    return this;
  },
  down() {
    this.step--;
    return this
  },
  showStep() {
    console.log(this.step)
    return this;
  }
};

stepCount.up().up().down().showStep().down().showStep();

Sign up to request clarification or add additional context in comments.

2 Comments

I got error (down is not a function!!!!) try this code: ``` stepCount.up().up().down().showStep().down().showStep(); ```
updated the answer,please check it
0

This should do the job:

class Step {
    constructor(count) {
        this.step = count;
    }

    up() {
        this.step++;
        return this;
    }

    down() {
        this.step--;
        return this;
    }
}

console.log(new Step(5).up().up().step); // 7

1 Comment

I prefer to code without class here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.