Kata – Tribonacci Sequence

I did a codewars Kata tonight and it went quickly for once! It was called the Tribonacci sequence and it is creating a fibinacci sequence that sums three numbers instead of two. Conceptually it is pretty understandable, and my resulting code was relatively slim.

function tribonacci(signature,n){
 if (n===0) return []; //short circuit on 0
 let outArray = [...signature]; //start the sequence
 for (let i=3; i<n; i++){
     outArray.push(outArray[i-3]+outArray[i-2]+outArray[i-1])
 }
 if (n<=3){ //return the right # if it is below 4
     return outArray.slice(0,n);
 }
  return outArray //otherwise smooth sailing
}

tribonacci([1,2,3],20);

This time I expected all sorts of weird edge cases, but I passed the test on the first shot! I actually liked the simplifications that the top rated answer had, so I’ll refactor a few into the result below

function tribonacci(signature,n){
 for (let i=3; i<n; i++){
     signature.push(signature[i-3]+signature[i-2]+signature[i-1])
 }
 return signature.slice(0,n); //this line alone will return empty
} // on n=0 and correct when n<=3

I think this is most likely one of the easier katas I have run into, but it’s still nice to get a quick win in every once in a while. I thought it was interesting to see how they used the signature variable as opposed to holding it in a new one. That saved a line right there.

Tell me what you think.

This site uses Akismet to reduce spam. Learn how your comment data is processed.