DEV Community

loading...

Discussion on: Daily Challenge #12 - Next Larger Number

Collapse
shayaulman profile image
Shaya Ulman

This was my solution on CodeWars (JS):

//helper functions
const nearestUp = (input, lookup) => lookup.sort((a, b) => a - b).find(n => n > input);
const isArrayDecreasing = (array) => !(array.reduce((n, item) => n !== false && item >= n && item))

//main function
const nextBigger = n =>  {
  const numberSplitted = String(n).split('');
  for (let i = numberSplitted.length-1; i > 0; i--) {

    if (isArrayDecreasing([numberSplitted[i], numberSplitted[i-1]])){
      let nextHigherNumber = numberSplitted.splice(0, i-1);
      const firstToReplace = nearestUp(numberSplitted[0], numberSplitted);

      numberSplitted.sort((a , b) => a - b);
      nextHigherNumber.push(firstToReplace);
      numberSplitted.splice(numberSplitted.indexOf(firstToReplace), 1);

      nextHigherNumber = nextHigherNumber.concat(...numberSplitted)[0] === '0' ? -1 : Number(nextHigherNumber.concat(...numberSplitted).join(''));
      return nextHigherNumber;
    }
  }
  return -1;
}