Reputation: 160
I need to autogenerate a new four digit code that everytime I run the function the value increments. Such as 0001 the first time, 0002, 0003 and so on. This is the code I have so far, the format is okay but I cant get it to increment the value automatically. I know it's probably a while loop but I wanted to ask advise on how it should be done. Thank you.
function pad(n){
var num = 1;
var string = "" + num;
var pad = "0000";
n = pad.substring(0, pad.length - string.length) + string;
num++;
return n;
}
Upvotes: 2
Views: 2813
Reputation: 2346
UPD: I like andlrc's solution. It's more JS way than my =)
===
better solution - without global variable (OOP style)
function ID(start){
this.num = start || 0;
}
ID.prototype._to4DigitString = function(){
return ("0000"+this.num).slice(-4);
}
ID.prototype.current = function(){
return this._to4DigitString(this.num);
}
ID.prototype.next = function(){
return this._to4DigitString(++this.num);
}
//then you can use it
var id = new ID();
id.next(); // "0001"
id.current(); // "0001"
id.next(); // "0002"
Upvotes: 0
Reputation: 24802
You could use Number.prototype.toLocaleString(locales, options)
.
In particular, its minimumIntegerDigits
option makes you able to left-pad numbers to the required number of digits :
var number = 12;
number.toLocaleString(undefined, {useGrouping: false, minimumIntegerDigits: 4})
This will display 0012
.
Leaving the locales undefined tells the function to work with the OS's locale, which should always be ok since we switched off grouping and aren't displaying currencies nor decimal numbers.
useGrouping
is the only option whose default doesn't work well with your need, if left unspecified it will instead display 0 012
for my locale (fr_FR) and probably 0,012
for the en_US
.
Upvotes: 1
Reputation: 47099
You should use Joke aside you can avoid polluting the global scope with a closure:left-pad
for this
var pad = (function(num) {
return function() {
var str = String(num++);
while (str.length < 4) str = "0" + str;
return str;
}
})(1);
Usage:
console.log(pad()); // "0001"
console.log(pad()); // "0002"
console.log(pad()); // "0003"
Upvotes: 7
Reputation: 6381
you need to keep the value of num
outside function scope
otherwise, it will be 1
every time you invoke it
here is the solution:
var num = 1;
function pad(n){
var string = "" + num;
var pad = "0000";
n = pad.substring(0, pad.length - string.length) + string;
num++;
return n;
}
also, to make it more reusable, you can do the following (which I think you intended to do):
var num = 1;
function pad(n){
var string = "" + n;
var pad = "0000";
n = pad.substring(0, pad.length - string.length) + string;
return n;
}
pad(num++); // 0001
pad(num++); // 0002
Upvotes: 3