Change number to corresponding letters - javascript

My question is how do I get the corresponding letter(s) from a number.
So
0 => 0 // 0 stays 0
1 => A
2 => B
3 => C
26 => Z
27 => AA
28 => AB
55 => AC
702 => ZZ
The number will definitely not be over 702.
Is there some kind of method I can use to do this?

Split the number into parts by doing a modulo by 26, then use String.fromCharCode to convert it to a character:
function numToExcelColumnName(n){
if(!n) return 0
n-- //Make 0 => A
const lower = n % 26
const upper = Math.floor(n / 26)
return (
upper
? String.fromCharCode(65 + upper - 1)
: ''
)
+ String.fromCharCode(65 + lower)
}
You can even extend this code to handle numbers above 702 as well by adding a loop:
function numToExcelColumnName(n){
if(!n) return 0
let output = ''
while(n){
n--
output = String.fromCharCode(65 + n % 26) + output
n = Math.floor(n / 26)
}
return output
}

For single characters like A,B... you can get the number easily by
num = ord(x)-65 where x is the corresponding character (A,B...)
For Double letters like (AB,BG,..)
num = ord(str[0]-65)*26+(str[1]-65) where str = xy where x and y are corresponding characters

I liked the challenge, so I wrote the following code:
function NumbersToLetters(num) {
var letArr=[];
function numToLet(letterArray, number) {
if(number>0) {
var whole=Math.floor((number-1)/26);
var reminder=(number-1)%26;
letterArray.unshift(String.fromCharCode(65+reminder));
numToLet(letterArray, whole);
}
};
numToLetters(letArr, num);
return letArr.length?letArr.join(""):"0";
}
To be used:
NumbersToLetters(num);

Related

JavaScript: LeetCode 'Plus One' recursion timeout problem

Plus one- leetcode problem
Problem:
You are given a large integer represented as an integer array digits,
where each digits[i] is the ith digit of the integer. The digits are
ordered from most significant to least significant in left-to-right
order. The large integer does not contain any leading 0's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
Constraints:
1 <= digits.length <= 100
0 <= digits[i] <= 9
digits does not contain any leading 0's.
My solution:
// [9] becomes [1,0]
var plusOne = function(digits) {
let len = digits.length;
//count array backwards
for(let i = len-1; i >= 0; i--) {
// if the currently indexed value is 9, we will zero it (line 14)
// we will also check if the previous entry is 9 via recursion (line 19)
// if it is not 9, we increment it by 1 and return 'digits' (lines 22, 23)
// if there is no previous entry we prepend one and return 'digits' (lines 16, 17)
if(digits[i] == 9) {
digits[i] = 0;
if(!digits[i - 1]){
digits.unshift(1);
return digits;
} else {
plusOne(digits.slice(0, i-1));
}
} else {
digits[i] = digits[i] + 1;
return digits;
}
}
};
let array = [9,9,9];
console.log(plusOne(array));
// This code breaks on input:
// [9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]
The difficulty with this problem is with 9's, which naturally increment the place value of its more significant neighbor.
I address this problem with recursion. (As you can read in the code comments).
The problem is that I am getting a 'Time limit exceeded' error on Leetcode on the following input:
[9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9].
Though it appears to pass all other test cases.
Is this a stack size issue? Is there a way to optimize the space complexity of the above code?
Thank you very much.
I have no idea how to reduce the time/space complexity of the problem as I am new to recursion.
"Is there a way to optimize the space complexity of the above code?"
Yes, remove the unnecessary recursive call. It does nothing:
// [9] becomes [1,0]
var plusOne = function(digits) {
let len = digits.length;
//count array backwards
for(let i = len-1; i >= 0; i--) {
// if the currently indexed value is 9, we will zero it (line 14)
// we will also check if the previous entry is 9 via recursion (line 19)
// if it is not 9, we increment it by 1 and return 'digits' (lines 22, 23)
// if there is no previous entry we prepend one and return 'digits' (lines 16, 17)
if(digits[i] == 9) {
digits[i] = 0;
if(i === 0){
digits.unshift(1);
return digits;
}
} else {
digits[i] = digits[i] + 1;
return digits;
}
}
};
let array = [9,9,9];
console.log(plusOne(array));
There's no need to traverse the entire input. The function can stop as soon as there's no carry to the next decimal place.
var plusOne = function(digits) {
// a single digit add that returns [sum, carry]
const incr = num => num === 9 ? [0, 1] : [num + 1, 0];
// reverse the input so we can go least significant to most
const reversed = digits.reverse();
let index = 0,
carry = 0,
sum = 0;
// increment digits, stopping as soon as there's no carry
// worst case is a run through a lot of 9s
do {
[sum, carry] = incr(reversed[index]);
reversed[index] = sum;
} while (carry && ++index < reversed.length)
// push a 1 if we got to the most significant digit with a carry
if (carry) reversed.push(1);
return reversed.reverse();
}
// here it is running pretty fast on 10x the largest input
let lottaNines = Array(1000).fill(9);
console.log(plusOne(lottaNines))
you can do that :
const plusOne = arr =>
{
let
rem = 1
, res = []
;
for (let i=arr.length-1; i >= 0; i--)
{
res[i] = arr[i] + rem;
rem = res[i] > 9 ? 1 : 0;
if (rem)
res[i] = 0;
}
if (rem )
res.unshift(1);
return res;
}
console.log( JSON.stringify(plusOne([1,2,3])))
console.log( JSON.stringify(plusOne([9])))
const outOfMaxInteger =[9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9]
console.log( JSON.stringify(plusOne(outOfMaxInteger)))
in fact it amounts to making a school addition:
const arrAdd= (arrA,arrB) =>
{
let
iA = arrA.length -1
, iB = arrB.length -1
, res = []
, rem = 0
;
for (let i = 1 + Math.max(iA,iB); i--; iA--,iB--)
{
res[i] = rem + (iA<0?0:arrA[iA]) + (iB<0 ? 0:arrB[iB]);
rem = 0 | (res[i] / 10);
res[i] %= 10;
}
if (rem) res.unshift(rem);
return res;
}
console.log( ' [1,2,3] + [1] =', JSON.stringify(arrAdd( [1,2,3], [1])))
console.log( '[1,2,3,0] + [8,0] =', JSON.stringify(arrAdd( [1,2,3,0],[8,0])))
console.log( ' [1,9,3] + [8] =', JSON.stringify(arrAdd( [1,9,3], [8])))
console.log( ' [9] + [9] =', JSON.stringify(arrAdd( [9], [9])))

Alpha numeric sequence generation using javascript

I need to generate the custom sequence as below using javascript based on input. For ex: if i provide the input isAA1 then output should be AA2 and if provided input as AA9 then the output should be AB0. I can do with the if else by creating the token's but it looks like we need to keep so many if else condition's. Wanted to know the more efficient way to handle this.
AA0
AA1
AA2
AA3
AA4
AA5
AA6
AA7
AA8
AA9
AB0
AB1
AB2
AB3
AB4
AB5
AB6
AB7
AB8
AB9
AC0
AC1
.
.
.
ZZ9
Using reduceRight() you can iterate over the spread string in reverse, incrementing each character as necessary using the character's charCodeAt() value adjusted by its offset from 0, and cycling it based on its remainder (%) for the appropriate cycle length (10 for integers, 26 for letters). The accumulator tracks whether to sum on the next iteration, as well as the result string.
const incrementAlphaNumeric = (str) => {
let iter, min, len;
return [...str]
.reduceRight((a, c, i) => {
let code = c.charCodeAt();
if (code >= 48 && code <= 57) { // [0-9]
min = 48;
len = 10;
} else if ((code >= 65 && code <= 90)) { // [A-Z]
min = 65;
len = 26;
}
iter = code - min + a.sum;
a.res[i] = String.fromCharCode(iter % len + min);
a.sum = Math.floor(iter / len);
return a;
}, { res: [], sum: 1 })
.res
.join('');
}
console.log(incrementAlphaNumeric('AA0')); // AA1
console.log(incrementAlphaNumeric('AA9')); // AB0
console.log(incrementAlphaNumeric('AZ9')); // BA0
console.log(incrementAlphaNumeric('ZZ9')); // AA0
I had a little time on my hands, and this seemed like a fun challenge, so I went ahead and built a function that accepts any string of uppercase letters and/or numbers. I realize it might be a little bit overkill for the requirements of the question, but it does satisfy all of the requirements, and someone else stumbling across this question in the future might find this helpful.
It works by converting the right-most character to its respective character code, incrementing it by 1, and checking if the resulting character code is outside of the A-Z or 0-9 range. If it is outside of its range, we reset it to its "base value" (A or 0) and set a carry flag (this is very similar to how binary adder circuits work). If the carry flag is set, we recursively call the function using the next-to-last character as our new "right-most" character until we no longer need to carry. At which point, we simply return the new string.
increment('AA0') > 'AA1
increment('AA9') > 'AB0
increment('ZZ9') > 'AA0
increment('AZ9BE') > 'AZ9BF
const A = 65
const Z = 90
const ZERO = 48
const NINE = 57
const isDigit = (char) => char >= 48 && char <= 57
const incDigit = (char) => char + 1 > NINE ? ZERO : char + 1
const incLetter = (char) => char + 1 > Z ? A : char + 1
const codeToChar = (code) => String.fromCharCode(code)
const setChar = (index, char, str) => {
const charArr = [...str]
charArr.splice(index, 1, char)
return charArr.join('')
}
const increment = (str, place = str.length - 1) => {
if (place < 0) return str;
const char = str.charCodeAt(place)
const nextChar = isDigit(char) ? incDigit(char) : incLetter(char)
const carry = nextChar - char !== 1;
str = setChar(place, codeToChar(nextChar), str)
if (carry)
return increment(str, --place)
else return str
}
let demoStr = 'AA0'
setInterval(() => {
demoStr = increment(demoStr)
console.log(demoStr)
}, 25)
You could use this next() function, which increments the letters of the input string by converting them to base 26 numeric strings and back whenever an overflow is detected from incrementing the decimal portion of the input string:
const next = (() => {
const charCodeA = 'A'.charCodeAt(0);
const to = (replacer, string) => string.replace(/./g, replacer);
const padStart = (string, { length }, pad) => string.padStart(length, pad);
const truncate = (string, { length }) => string.slice(-length);
const letter = (base26String) => String.fromCharCode(
parseInt(base26String, 26) + charCodeA
);
const base26 = (letterString) => (
letterString.charCodeAt(0) - charCodeA
).toString(26);
const increment = (numbersString, radix) => (
parseInt(numbersString, radix) + 1
).toString(radix);
return (prev) => {
const [, prevL, prevD] = prev.match(/^([A-Z]+)([0-9]+)$/);
const nextD = padStart(increment(prevD, 10), prevD, '0');
const carry = nextD.length > prevD.length;
const nextL = carry
? padStart(to(letter, increment(to(base26, prevL), 26)), prevL, 'A')
: prevL;
return truncate(nextL, prevL) + truncate(nextD, prevD);
};
})();
console.log(next('AA0')); // AA1
console.log(next('AZ9')); // BA0
console.log(next('ZZ9')); // AA0
console.log(next('AAA00')); // AAA01
console.log(next('AZZ09')); // AZZ10
console.log(next('AZZ99')); // BAA00
console.log(next('ZZZ99')); // AAA00
References
String.prototype.charCodeAt()
String.prototype.replace()
String.prototype.padStart()
String.prototype.slice()
String.fromCharCode()
parseInt()
Number.prototype.toString()
String.prototype.match()
You could take two function for gettign a deciaml or the fancy value and check if the last digit is nine.
function increment(value) {
const
decimal = s => Array
.from(s, v => parseInt(v, 36) - 10)
.reduce((s, v) => s * 26 + v, 0),
fancy = n => Array
.from(n.toString(26), v => (parseInt(v, 26) + 10).toString(36))
.join('')
.toUpperCase(),
[left, right] = value.match(/\D+|\d+/g);
if (value === 'ZZ9') return 'AA0';
return right === '9'
? fancy(decimal(left) + 1) + '0'
: left + (+right + 1);
}
console.log(increment('AA0')); // AA1
console.log(increment('AZ9')); // BA0
console.log(increment('ZZ9')); // AA0

Sum a negative number's digits

'Write a function named sumDigits which takes a number as input and
returns the sum of each of the number's decimal
digits.'
How can I sum the digits with the first digit being negative?
For example: sumDigits(-32); // -3 + 2 = -1;
I was able to solve it partially.
function sumDigits(number) {
return Math.abs(number).toString().split("").reduce(function(a, b) {
return parseInt(a) + parseInt(b);
}, 0);
}
console.log( sumDigits(-32) );
Simple math and recursion make short work of this problem.
Recall that when you divide a number by 10, the remainder is its rightmost decimal digit and the integer part of the quotient is the number formed by the remaining digits. In other words:
let n = 5678;
console.log(n % 10); // => 8
console.log(Math.floor(n / 10)); // => 567
With this in mind, summing a number's digits is a straightforward recursive procedure:
Procedure(n)
Divide n by 10.
Set digit to the remainder.
Set n to the integer part of the quotient.
If n = 0, return digit.
Otherwise, return digit + Procedure(n)
Keeping the sign for the leftmost digit adds a small amount of complexity, but not much. Here's how it looks in JavaScript:
function digitSum(n, sign=1) {
if (n < 0) {
sign = -1; // Save the sign
n = Math.abs(n);
}
const digit = n % 10; // Remainder of |n÷10|
n = Math.floor(n / 10); // Integer part of |n÷10|
if (n === 0) {
return sign * digit; // No digits left, return final digit with sign
}
return digit + digitSum(n, sign); // Add digit to sum of remaining digits
}
console.log(digitSum(32)); // => 5
console.log(digitSum(-32)); // => -1
Here is a way to do it with Array.prototype.reduce().
Stringify the input and split it on each character.
Iterate over the characters with reduce.
Initialize the accumulator with a sum of 0 and a multiplier of 1.
If the first character is a -, set the multiplier to -1
For the subsequent characters, multiply the digit with the multiplier and add it to the sum. Then set the multiplier back to 1 so the next digits will only be multiplied by 1.
const sumDigits = x => [...`${x}`].reduce(({ sum, mult }, x, i) => {
return i === 0 && x === '-' ? { sum: 0, mult: -1 } : { sum: sum + mult * x, mult: 1 };
}, { sum: 0, mult: 1 }).sum;
console.log(sumDigits(-32)); // -1
console.log(sumDigits(32)); // 5
console.log(sumDigits(5555)); // 20
Here's a way you can do it without String conversion -
const sumDigits = (n = 0) =>
n < 0
? n > -10
? n
: (-n % 10) + sumDigits (n / 10 >> 0)
: n < 10
? n
: (n % 10) + sumDigits (n / 10 >> 0)
console.log(sumDigits(-321))
// (-3 + 2 + 1)
// => 0
console.log(sumDigits(321))
// (3 + 2 + 1)
// => 6
The same answer using imperative style -
const sumDigits = (n = 0) =>
{ if (n < 0)
if (n > -10)
return n
else
return (-n % 10) + sumDigits (n / 10 >> 0)
else
if (n < 10)
return n
else
return (n % 10) + sumDigits (n / 10 >> 0)
}
console.log(sumDigits(-321))
// (-3 + 2 + 1)
// => 0
console.log(sumDigits(321))
// (3 + 2 + 1)
// => 6
An approach that does not require converting to a string adapted from another answer by #NinaScholz to a closely related question (for those that are bitwise shift operator challenged).
Converts the number to its absolute value, loops with modulus operator to sum the remainder after dividing by 10 until a ones value remains, and then subtracts the leftmost digit if the original number was negative.
const sumDigits = (n) => {
const negative = !!(n < 0);
let sum = 0;
let num = negative ? Math.abs(n) : n;
while (num) {
if (negative && num <= 10) {
sum -= num % 10;
} else {
sum += num % 10;
}
num = Math.floor(num / 10);
}
return sum;
};
console.log(sumDigits(-32));
// -1
You could take a different method for separating the digits and keep the first one with a possible sign.
'-32'.match(/-?\d/g)
returns
['-3', '2']
function sumDigits(number) {
return number.toString().match(/-?\d/g).reduce(function(a, b) {
return a + +b;
}, 0);
}
console.log(sumDigits(-32));
First, "decimal digits" means only the characters to the right of the decimal point. Converting the number to a string sets you up as JavaScript strings are arrays of characters. So, then it's just a matter of splitting out the decimal digits then summing them by iterating that array, then converting back to a number type.
//'Write a function named sumDigits which takes a number as input and returns the sum of each of the number's decimal digits.'
var a = 10.12345;
var b = -1012345;
function sumDigits(x){
var result = 0;
x = x.toString();
x = x.split('.')[1];
if (x == null){
//there's not decimal digits to sum!
return "there's not decimal digits to sum!"
}
for (var i = 0; i < x.length; i++) {
if (digit >= 0 && digit <= 9) { //just in case, probably unnecessary
var digit = Number(x[i]);
result = result + digit;
}
}
//if you care about negative uncomment this
//if(x[0] === "-"){
// result = result * -1;
//}
return result;
}
console.log(sumDigits(a));
console.log(sumDigits(b));
// try this to get the sum of negatives:
const sumOfNegative = (numbers) => {
let sum = 0;
numbers.forEach((number) => {
if (number < 0) {
sum += number;
}
});
return sum;
};

Most efficient method to check for range of numbers within number without duplicates

Given a number n , a minimum number min , a maximum number max , what is the most efficient method to determine
Number n is or is not within range , inclusive of , min - max
Number n does or does not contain duplicate numbers
Efficiency meaning here that the method or set of methods requires the least amount of computational resources and returns either true or false in the least amount of time
Context: Condition at if within a for loop which could require from thousands to hundreds of thousands of iterations to return a result; where milliseconds required to return true or false as to Number check could affect performance
At Profiles panel at DevTools on a collection of 71,3307 items iterated, RegExp below was listed as using 27.2ms of total 1097.3ms to complete loop . At a collection of 836,7628 items iterated RegExp below used 193.5ms within total of 11285.3ms .
Requirement: Most efficient method to return Boolean true or false given above parameters , within the least amount of time.
Note: Solution does not have to be limited to RegExp ; used below as the pattern returned expected results.
Current js utilizing RegExp re , RegExp.protype.test()
var min = 2
, max = 7
, re = new RegExp("[" + min + "-" + max + "](.)(?!=\1)", "g")
, arr = [81, 35, 22, 45, 49];
for (var i = 0; i < arr.length; i++) {
console.log(re.test(arr[i]), i, arr[i])
/*
false 0 81
true 1 35
false 2 22
true 3 45
false 4 49
*/
}
Associative arrays approach:
This has the advantage of being easily understandable.
function checkDigits(min, max, n) {
var digits = Array(10); // Declare the length of the array (the 10 digits) to avoid any further memory allocation
while (n) {
d = (n % 10); // Get last digit
n = n / 10 >>0; // Remove it from our number (the >>0 bit is equivalent to compose(Math.floor, Math.abs))
if (d < min || d > max || digits[d]) // Test if "d" is outside the range or if it has been checked in the "digits" array
return false;
else
digits[d] = true; // Mark the digit as existing
}
}
var min = 2
, max = 7
, arr = [81, 35, 22, 45, 49];
function checkDigits(min, max, n) {
var digits = Array(10); // Declare the length of the array (the 10 digits) to avoid any further memory allocation
while (n) {
d = (n % 10); // Get last digit
n = n / 10 >>0; // Remove it from our number (the >>0 bit is equivalent to compose(Math.floor, Math.abs))
if (d < min || d > max || digits[d]) // Test if "d" is outside the range or if it has been checked in the "digits" array
return false;
else
digits[d] = true; // Mark the digit as existing
}
return true;
}
for (var i = 0; i < arr.length; i++) {
console.log(checkDigits(min, max, arr[i]), i, arr[i])
}
Binary mask approach:
This replaces the Array with an integer that is in effect used as an array of bits. It should be faster.
function checkDigits(min, max, n) {
var digits = 0;
while (n) {
d = (n % 10);
n = n / 10 >>0;
if (d < min || d > max || (digits & (1 << d)))
return false;
else
digits |= 1 << d;
}
return true;
}
function checkDigits(min, max, n) {
var digits = 0;
while (n) {
d = (n % 10);
n = n / 10 >>0;
if (d < min || d > max || (digits & (1 << d)))
return false;
else
digits |= 1 << d;
}
return true;
}
Explanation for binary mask approach:
1 << d creates a bit mask, an integer with the d bit set and all other bits set to 0.
digits |= 1 << d sets the bit marked by our bit mask on the integer digits.
digits & (1 << d) compares the bit marked by our bit mask with digits, the collection of previously marked bits.
See the docs on bitwise operators if you want to understand this in detail.
So, if we were to check 626, our numbers would go like this:
________n_____626_______________
|
d | 6
mask | 0001000000
digits | 0000000000
|
________n_____62________________
|
d | 2
mask | 0000000100
digits | 0001000000
|
________n_____6_________________
|
d | 6
mask | 0001000000
digits | 0001000100
^
bit was already set, return false
Solution 1
test using regex
var min = 2;
var max = 7;
res = "";
arr = [81, 35, 22, 45, 49]
arr.push("");
regex=new RegExp("[" + min + "-" + max + "](.)(?!=\1)", "g")
var result = arr.reduce(function(a, b) {
if (regex.test(a)) {
res = res + a + " is true\n"
} else {
res = res + a + " is false\n"
};
return b
});
console.log(res)
The reduce method is different in a sense that it is like a generator function like in python (produces output on the fly)
Its simply loops through each elements in an array using a callback function. I cannot say how efficient is the reduce function.
Nevertheless consider two elements in the array
81 35
^
take this value take the result
and do something from the previous
element and add it
to the result computed
for this element
further information https://msdn.microsoft.com/en-us/library/ff679975%28v=vs.94%29.aspx
SOlution 2
Using list to store value and their boolean
var min = 2;
var max = 7;
res = [""];
arr = [81, 35, 22, 45, 49]
arr.push("");
regex=new RegExp("[" + min + "-" + max + "](.)(?!=\1)", "g")
var result = arr.reduce(function(a, b) {
if (regex.test(a)) {
res.push([a,true])
} else {
res.push([a,false])
};
return b
});
console.log(res)

Format a Number, Exactly Two in Length?

I have an integer that is less then 100 and is printed to an HTML page with JavaScript. How do I format the integer so that it is exactly two digits long? For example:
01
02
03
...
09
10
11
12
...
Update
This answer was written in 2011. See liubiantao's answer for the 2021 version.
Original
function pad(d) {
return (d < 10) ? '0' + d.toString() : d.toString();
}
pad(1); // 01
pad(9); // 09
pad(10); // 10
String("0" + x).slice(-2);
where x is your number.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
String(number).padStart(2, '0')
Just use the following short function to get the result you need:
function pad2(number) {
return (number < 10 ? '0' : '') + number
}
A direct way to pad a number to the left in Javascript is to calculate the number of digits by log base 10.
For example:
function padLeft(positiveInteger, totalDigits) {
var padding = "00000000000000";
var rounding = 1.000000000001;
var currentDigits = positiveInteger > 0 ? 1 + Math.floor(rounding * (Math.log(positiveInteger) / Math.LN10)) : 1;
return (padding + positiveInteger).substr(padding.length - (totalDigits - currentDigits));
}
The rounding factor fixes the problem that there is no way to get an exact log of powers of 10, for example Math.log(1000) / Math.LN10 == 2.9999999999999996
Of course one should add validation of the parameters.
// Return a string padded
function FormatMe(n) {
return (n<10) ? '0'+n : n;
}
function leftFillNum(num, targetLength) {
return num.toString().padStart(targetLength, '0');
}
console.log(leftFillNum(3,2)); // ==> returns '03'
console.log(leftFillNum(33,2)); // ==> returns '33'
console.log(leftFillNum(3,4)); // ==> returns '0003'
console.log(leftFillNum(33,5)); // ==> returns '00033'
function padLeft(a, b) {
var l = (a + '').length;
if (l >= b) {
return a + '';
} else {
var arr = [];
for (var i = 0; i < b - l ;i++) {
arr.push('0');
}
arr.push(a);
return arr.join('');
}
}
I usually use this function.
function pad(n, len) {
let l = Math.floor(len)
let sn = '' + n
let snl = sn.length
if(snl >= l) return sn
return '0'.repeat(l - snl) + sn
}
Usage Example
pad(1, 1) // ==> returns '1' (string type)
pad(384, 5) // ==> returns '00384'
pad(384, 4.5)// ==> returns '0384'
pad(5555, 2) // ==> returns '5555'
I use regex to format my time such as
const str = '12:5'
const final = str.replace(/\d+/g, (match, offset, string) => match < 10 ? '0' + match : match)
output: 12:05
Improved version of previous answer:
var result = [...Array(12)].map((_, i) => zeroFill(i + 1, 2));
function zeroFill(num, size) {
let s = num + '';
while (s.length < size) s = `0${s}`;
return s;
}
console.log(result)
lodash has padStart, https://lodash.com/docs/4.17.15#padStart
padStart(1, 2, '0')
it will pad 1 => 01, it wont take care of negative numbers, as - will be considered as padding
const threeDigit = num => num.toString().padStart(3 , '0');
The function converts a number to a string and then returns a three-digit version of the number

Categories

Resources