0

I'v heard this question, and I'm unsure as how to solve it.

The requirement is: implement the function from so it will preform like so on the following scenario:

var x = from(3);
console.log(x()); //outputs 3
console.log(x()); //outputs 4
//TODO: implement from()

I tried something like:

function from(val) {
  var counter = val;
  return function(){
    return counter+=1;
  }
}

But the first time I run it, it increments the value, So that's a no go.

4
  • 1
    Have you tried to implement it at all yet? Commented Jun 14, 2015 at 18:37
  • So, what went wrong with your implementation? Commented Jun 14, 2015 at 18:37
  • did you try something out yourself? Commented Jun 14, 2015 at 18:37
  • 2
    Post-increment will do the trick, instead of returning counter+=1 return counter++, that way counter is first returned, then incremented. Commented Jun 14, 2015 at 18:41

3 Answers 3

5
var x = from(3);

function from(startValue) {
   var counter = startValue;
   return function() {
     return counter++;
   }
}

console.log(x()); //outputs 3
console.log(x()); //outputs 4
Sign up to request clarification or add additional context in comments.

Comments

2

The most straightforward solution would be to simply subtract 1 from counter:

function from(val) {
    var counter = val - 1;
    return function(){
        return counter += 1;
    }
}

However, in this case you can make use of the postfix ++ operator, because in counter++, the value of counter is increased by one, but the old value of counter is returned.
You should be good to go with

function from(val) {
    var counter = val;
    return function(){
        return counter++;
    }
}

For completeness, the equivalent to counter += 1 would be ++counter.

Comments

0

function from(val) {
  var counter = val;
  return function() {
    return counter++;
  }
}

var x = from(3);
alert(x()); //outputs 3
alert(x()); //outputs 4
alert(x()); //outputs 5
alert(x()); //outputs 6
alert(x()); //outputs 7
alert(x()); //outputs 8

Try this

Comments

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.