JSFiddle - React, Tailwind, and code Playground

by konijn_gmail_com

JavaScript

//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...