Skip to content

Instantly share code, notes, and snippets.

@renatocassino
Last active August 11, 2018 22:49
Show Gist options
  • Save renatocassino/7b1589776ea9eb4e9bd6705e1bb7498c to your computer and use it in GitHub Desktop.
Save renatocassino/7b1589776ea9eb4e9bd6705e1bb7498c to your computer and use it in GitHub Desktop.
2048-moveUpTry3.js
/**
* @param line Array Old board array
*/
const moveLineUp = (line) => { // One uniq parameter
// Internal function to recursive
const moveLineUpInner = (counter, lineWithoutZeros, results=[]) => {
// now we have only a counter
if(counter === 0) return results; // If 0, return
if (lineWithoutZeros.length === 0) { // If all numbers different of 0 are empty
return moveLineUpInner(counter - 1, [], [...results, 0]); // Add 0
}
const currentValue = lineWithoutZeros[0]; // HEAD
if(currentValue === lineWithoutZeros[1]) {
const total = currentValue + lineWithoutZeros[1];
return moveLineUpInner(counter - 1, lineWithoutZeros.slice(2), [...results, total]); // Remove 2 in lineWithoutZeros, because two blocks joined in one
}
return moveLineUpInner(counter - 1, lineWithoutZeros.slice(1), [...results, lineWithoutZeros[0]]); // Add number and slice line and lineWithoutZeros
};
return moveLineUpInner(line.length, line.filter((n)=>n > 0));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment