Breaking down the problem into smaller tasks and solving them with concise functions can be an effective approach. Here's a breakdown of how we tackle the problem:
- Convert the given string into an array
- Divide the array into chunks of three digits, or as close to three as possible
- Filter out any chunks that do not contain exactly three numbers
- Convert each chunk of 3 'number' strings into a single number
- Determine the largest number from the set
- Return the largest number found
If speed is your primary concern, this may not be the most efficient solution for you. However, if you prefer a solution composed of small, reusable pieces, then this method could be suitable.
const splitIntoAllChunks = size => array => Object.values(
array
.reduce((prev, _, i) => ({
...prev,
[i]: array.slice(i, i + size),
}), {})
);
const splitIntoThrees = splitIntoAllChunks(3);
const isLength = length => array => array.length === length;
const stringArrayToNumber = array => Number(array.join(''));
const getMax = (champ, challenger) => challenger > champ ? challenger : champ;
const example = "184727158129123"
const result = splitIntoThrees(example.split(''))
.filter(isLength(3))
.map(stringArrayToNumber)
.reduce(getMax, 0);
console.dir(result);
If you prefer sticking closer to your original solution, you can make some adjustments like so:
const testData = "1234596789"
function largestThreeDigitNum(numString){
let numberSize = 3;
let largestThreeNumber = 0;
for (let i = 0; i < numString.length - (numberSize - 1); i++){
const thisNumber = Number(numString.slice(i, i + 3))
if(thisNumber > largestThreeNumber){
largestThreeNumber = thisNumber;
}
}
return largestThreeNumber;
}
console.dir(largestThreeDigitNum(testData))