DEV Community

Discussion on: Daily Challenge #260 - Subtract the Sum

Collapse
 
willsmart profile image
willsmart • Edited

A quick JS one:

First up, set up the base fruit mapping by splitting that string:

const
  inputFruitMappingString = `1-kiwi
2-pear
...other entries...
99-apple
100-pineapple`,
  baseFruitMapping = Object.fromEntries(
    inputFruitMappingString.split('\n').map(line => line.split('-'))
  )

The fruit-fetching-function itself:

function fruitForIndex(i) {
  return baseFruitMapping[i] ??
    fruitForIndex(
      [...String(i)].reduce((acc, digit) => acc - digit, i)
    );
}

The guts of that is: [...String(i)].reduce((acc, digit) => acc - digit, i)
Breaking that up:

  • String(i): i is a number so to split it into characters, render it into a standard decimal string
  • [...String(i)]: Easy way to split the string into chars
  • [...String(i)].reduce((acc, digit) => acc - digit, i): The reduce function is passed the number itself as its initial value and then goes through the array of digits, subtracting each from the running total.

Bit of sanity checking...

// Debug version of the function
function fruitForIndex(i) {
  console.log(i), 
  return baseFruitMapping[i] ?? fruitForIndex([...String(i)].reduce((acc, digit) => acc - digit, i));
}

> fruitForIndex(1)
1
< "kiwi"

> fruitForIndex(100)
100
< "pineapple"

> fruitForIndex(101)
101
99
< "apple"

> fruitForIndex(200)
200
198
180
171
162
153
144
135
126
117
108
99
< "apple"


Note that it's worth making sure you have a modern JS engine
Caniuse for Object.fromEntries
Caniuse for ??