//https://blogs.sap.com/2020/04/27/sap-community-coding-challenge-nr.2/
/*
- This demonstrates
* IIFE for the reusable part
* Imperative for the solution
* A dash of FP to update the cache
- This does no makes use of any library
- This could have been shorter, the following was considered:
>value = value & 1 ? value*3+1 : value / 2;
>but not all developers are that familiar with ternary
>we could have let updateCache return terms.length + offset
>it would have saved a whole line
>it would also let updateCache do something that is not on the tin (name)
>so definitely a bad idea
>most developers might go for `value%2` for even,
>&1 is nice reminder that everything is binary underneath
>agony was experienced over the `offset` variable name,
>nothing better came to mind
>Obviously, without reuse in mind, this could have been far shorter
>Avoided memoization, since that would require recursion, not the biggest fan
- This should be easy to read
- The main focus was to make getCollatzSequenceLength reusable
- This counts on ES6 for let/const
- Whitespace: 2 spaces or death
- Variable names should be Spartan or informative
- Creativity: meh, it seems everybody thought of caching :/
*/
let getCollatzSequenceLength = (() => {
const lengthsCache = {};
function updateCache(terms, offset) {
terms.reverse().forEach((value, index) => lengthsCache[value] = index + offset + 1);
}
function getLength(value) {
let terms = [value];
while (value != 1) {
//odd -> triple and add 1
//even -> halve it
if (value & 1) {
value = value * 3 + 1;
} else {
value = value / 2;
}
//If we cached this value, then use it after updating the cache
if (lengthsCache[value]) {
updateCache(terms, lengthsCache[value]);
return terms.length + lengthsCache[value];
}
//Build the...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.