Skip to content

Instantly share code, notes, and snippets.

@misterussell
Created June 15, 2017 17:00
Show Gist options
  • Save misterussell/abc55216af14b6f67b5a219224ed557f to your computer and use it in GitHub Desktop.
Save misterussell/abc55216af14b6f67b5a219224ed557f to your computer and use it in GitHub Desktop.
Codewars Test 3
function combineValues(data) {
// compute the value of the last 3 vals
return getLastThree(data).reduce((a, b) => {
return a + b;
}, 0);
}
function getLastThree(data) {
// if the length is 3 we don't need to pull any specific locations as we are computing against all of these
if (data.length > 3) {
return [data[data.length -1 ], data[data.length - 2], data[data.length -3]];
}
else return data;
}
function tribonacci(signature, n) {
// first add together the three digits of signature to our new array to avoid mutation
let newSignature = [...signature];
// declare storage for our new values that will be computed
let next;
// compute n new values
for (var i = 0; i < n-3; i++) {
next = combineValues(newSignature)
newSignature.push(next);
}
// return our new array
if (n === 0) {
return [];
} else if (n <= 3) {
// if n is 3 or lower return that many locations of signature
// [0, 0, 1], 2
// [0, 1, 2]
return signature.filter((num, i) => {
if (i < n) {
return true;
}
});
} else {
return newSignature;
}
}
console.log(tribonacci([1,1,1],10));
// [1,1,1,3,5,9,17,31,57,105]
console.log(tribonacci([0,0,1], 10));
// [0,0,1,1,2,4,7,13,24,44]
console.log(tribonacci([0,1,2], 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment