Last active
August 11, 2018 23:46
-
-
Save renatocassino/87a3fbf97a514ac9314bafce701c6387 to your computer and use it in GitHub Desktop.
2048-moveUpTry2.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param line Array Old board array | |
* @param result New array with new state. Start empty | |
* @param lineWithoutZerosMemoized array list of numbers in line without 0 | |
*/ | |
const moveLineUp = (line, results=[], lineWithoutZerosMemoized=null) => { | |
// line is used like a counter to add in results | |
if(line.length === 0) return results; // If line is empty, get out recursion | |
const lineWithoutZeros = lineWithoutZerosMemoized || line.filter((n)=>n > 0); | |
if (lineWithoutZeros.length === 0) { | |
return moveLineUp(line.slice(1), [...results, 0], []); // Add 0 and remove one in array | |
} | |
const [currentValue, ...tail] = lineWithoutZeros; // <----- Head and Tail | |
if(currentValue === lineWithoutZeros[1]) { | |
return moveLineUp(line.slice(1), [...results, currentValue + lineWithoutZeros[1]], lineWithoutZeros.slice(2)); // Remove 2 in lineWithoutZeros, because two blocks joined in one | |
} | |
return moveLineUp(line.slice(1), [...results, lineWithoutZeros[0]], tail); // Add number and slice line and lineWithoutZeros | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment