Codewars: Reverse or Rotate
Towards optimization and restructuring

One of downsides of the initial revrot approach is that all nested functions test, reverse and rotate will be redundantly recreated on each revrot call.Instead - define them as top-level functions with meaningful names.

Next, the program lacks 2 edge cases:


when input string contains one single digit and size of required chunk is also 1 (ex. revrot("3", 1)). It's worth to catch that case immediately and return the unchanged input string
when input string contains non-digit character


The intermediate arr array with for loop and slice calls (to get all chunks) is replaced with convenient String.match call on dynamic regex pattern new RegExp(`.{${size}}`, 'g') (matches substrings of specific length/size)



The final optimized approach:



const testCubes = s =&gt; Array.prototype.reduce.call(s, (acc, val) =&gt; acc + Number(val) ** 3, 0) % 2 === 0;
const strReverse = s =&gt; [...s].reverse().join("");
const rotateLeft = s =&gt; s.slice(1) + s.slice(0, 1);


function revrot(str, size) {
    let len = str.length;
    if (size &lt; 1 || !str || size &gt; len) return "";
    if (len === 1 &amp;&amp; size === 1) return str;
    if (/\D/.test(str)) {
        throw Error("Invalid numeric string");
    }
    let pat = new RegExp(`.{${size}}`, 'g');
    return str.match(pat).map(x =&gt; 
        testCubes(x) ? strReverse(x) : rotateLeft(x)
    ).join("");
}


console.log(revrot("123456987654", 6));
console.log(revrot("123456987653", 6));
console.log(revrot("66443875", 8));
console.log(revrot("563000655734469485", 4));
console.log(revrot("1", 1));
console.log(revrot("6644-d3875", 8));