Skip to content

Commit

Permalink
update increment function
Browse files Browse the repository at this point in the history
  • Loading branch information
Usaldudo committed Dec 14, 2023
1 parent b7d20a1 commit 2b3b258
Showing 1 changed file with 18 additions and 17 deletions.
35 changes: 18 additions & 17 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,25 +29,26 @@ function input(name, def) {
}

function increment(string, amount) {

// Extract string's number
var number = string.match(/\d+/) === null ? 0 : string.match(/\d+/)[0];

// Store number's length
var numberLength = number.length;
var leadingZeroes = number.startsWith("0");

// Increment number by the amount
number = (parseInt(number, 10) + parseInt(amount, 10)).toString();

// If there were leading 0s, add them again
if (leadingZeroes) {
while (number.length < numberLength) {
number = "0" + number;
// Extract string's numbers
var numbers = string.match(/\d+/g) || [];

// Increment the last number by the amount
var lastNumberIndex = numbers.length - 1;
var lastNumber = parseInt(numbers[lastNumberIndex], 10) || 0;
numbers[lastNumberIndex] = (lastNumber + parseInt(amount, 10)).toString();

// Reconstruct the string with incremented numbers and leading zeroes
var result = string.replace(/\d+/g, function (match) {
var currentNumber = numbers.shift();
if (match.startsWith("0")) {
while (currentNumber.length < match.length) {
currentNumber = "0" + currentNumber;
}
}
}
return currentNumber;
});

return string.replace(/[0-9]/g, "").concat(number);
return result;
}

const createVariable = (data) => {
Expand Down

0 comments on commit 2b3b258

Please sign in to comment.