Coding since 11yo, that makes it over 30 years now ~~~
Have a PhD in Comp Sci ~~~
Love to go on bike tours ~~~
I try to stay as generalist as I can in this crazy wide place coding is at now.
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 functionfunctionfruitForIndex(i){console.log(i),returnbaseFruitMapping[i]??fruitForIndex([...String(i)].reduce((acc,digit)=>acc-digit,i));}>fruitForIndex(1)1<"kiwi">fruitForIndex(100)100<"pineapple">fruitForIndex(101)10199<"apple">fruitForIndex(200)20019818017116215314413512611710899<"apple"
A quick JS one:
First up, set up the base fruit mapping by splitting that string:
The fruit-fetching-function itself:
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...
Note that it's worth making sure you have a modern JS engine
Caniuse for Object.fromEntries
Caniuse for ??