Created
July 7, 2022 10:45
-
-
Save luan0ap/fe80c332524134a69f7e6c6a8da12338 to your computer and use it in GitHub Desktop.
Rock, paper and scissors. Memoizer solution
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
const memoizer = (fn, initialState = null) => { | |
const _cache = initialState || {} | |
return (...params) => { | |
const _stringified = JSON.stringify(params) | |
if (_cache[_stringified] === undefined) { | |
const result = fn(...params) | |
_cache[_stringified] = result | |
return result | |
} | |
return _cache[_stringified] | |
} | |
} | |
const getWinner = memoizer((p1, p2) => { | |
const getSignal = (p1, p2) => { | |
const signals = ['rock', 'paper', 'scissors'] | |
const index = (signals.indexOf(p1) + signals.indexOf(p2)) - 1 | |
return ['paper', 'rock', 'scissors'][index] | |
} | |
return [p1, p2].indexOf(getSignal(p1, p2)) + 1 | |
}) | |
const rps = (p1, p2) => { | |
if (p1 === p2) { | |
return 'Draw!' | |
} | |
return `Player ${getWinner(p1, p2)} won!` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment