JSFiddle - React, Tailwind, and code Playground
by rexonms
JavaScript
// Function increment Array
// [2,7,4] would return [2,7,5]
const incrementArray = (numArray) => {
let arrayLength = numArray.length
let lastDigit = numArray[arrayLength-1]
if (arrayLength === 0) {
// Empty array
numArray = [1]
} else if (lastDigit < 9) {
// If last digit is not 9 add 1 to the last digit
numArray[arrayLength -1] = lastDigit + 1
} else {
// We now that the last number is 9
if(arrayLength === 1) {
// If there is only one number
numArray = [1,0]
} else {
// lets check from second last number
let counter = 0
for(let i = arrayLength - 1; i > -1; i--) {
let previousNum = numArray[i]
if (previousNum !== 9) {
// If previous numer is not nine then update the number
// and break the loop
numArray[i] = numArray[i] + 1
break
}
else {
numArray[i] = 0
counter++
}
// If all the numbers are 999 then add 1 at the be
if (counter === arrayLength) {
numArray.unshift(1)
}
}
// set the last number to 0
// we know that it is nine
numArray[arrayLength -1] = 0
}
}
return numArray
}
console.clear()
console.log(incrementArray([]), '[1]' )
console.log(incrementArray([0]), '[1]' )
console.log(incrementArray([1]), '[2]')
console.log(incrementArray([9]), '[1,0]')
console.log(incrementArray([1,2,3]), '[1,2,4]')
console.log(incrementArray([1,2,9]), '[1,3,0]')
console.log(incrementArray([1,8,9,9]), '[1,9,0,0]')
console.log(incrementArray([9,9,9]), '[1,0,0,0]')