2D Distance Memoization

node v10.24.1
version: 1.0.0
endpointsharetweet
const distance = (x1, y1, x2, y2) => { const d = Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) console.log(`calculating distance from (${x1}, ${y1}) to (${x2}, ${y2}) = ${d}`) return d } const distanceMemo = (x1, y1, x2, y2) => { distanceMemo._ = '_' in distanceMemo ? distanceMemo._ : {} const key = `${x1}${y1}${x2}${y2}` if (!(key in distanceMemo._)) { distanceMemo._[key] = distance(x1, y1, x2, y2) } return distanceMemo._[key] } distanceMemo(0, 0, 5, 5) distanceMemo(0, 0, 5, 5) distanceMemo(0, 0, 5, 5)
Loading…

no comments

    sign in to comment