-3

So i'd like to make a function that sequentially generates a number each execution, I was wondering how to do this in Javascript I need this to basically set an order to my items in mongoDB. How can I write a JS function that generates a number sequentially each time it's run? ex: 1... then run the function again...2 then again...3.

asked Jul 18, 2015 at 22:32
4
  • stackoverflow.com/questions/2282140/… Commented Jul 18, 2015 at 22:34
  • yield is still (too) rare in JavaScript implementations. Commented Jul 18, 2015 at 22:36
  • The "sad" thing here is that the mongodb tag in the question leads me to believe you actually wanted this: Create an Auto-Incrementing Sequence Field, yet just got "owned" for lack of research and asking more in terms of a javascript question than explaining what you were going to use it for. Commented Jul 19, 2015 at 2:37
  • @BlakesSeven how did I get owned? Commented Jul 19, 2015 at 18:43

1 Answer 1

2
var next = (function() {
 var v = 0;
 return function() {
 return v++;
}})();
console.log(next()); // 0
console.log(next()); // 1
console.log(next()); // 2
answered Jul 18, 2015 at 22:35
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.