Skip to content

Instantly share code, notes, and snippets.

@luan0ap
Created July 7, 2022 10:45
Show Gist options
  • Save luan0ap/fe80c332524134a69f7e6c6a8da12338 to your computer and use it in GitHub Desktop.
Save luan0ap/fe80c332524134a69f7e6c6a8da12338 to your computer and use it in GitHub Desktop.
Rock, paper and scissors. Memoizer solution
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