Created
August 18, 2019 10:38
-
-
Save MrTelanie/f20beaec02ddeb2ad29bde76d037177f to your computer and use it in GitHub Desktop.
reverse a function
This file contains 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 REV_FORM = Symbol("reverse-formula"); | |
const SCALE = 10; | |
function createReverseFormula(formula) { | |
const list = new Array(SCALE + 1).fill(0).map((_, i) => { | |
const inp = i / SCALE; | |
const out = formula(inp); | |
return { inp, out }; | |
}); | |
return output => { | |
let distance = Number.POSITIVE_INFINITY; | |
let closest; | |
list.forEach(({ inp, out }) => { | |
const dist = Math.abs(output - out); | |
if (dist < distance) { | |
distance = dist; | |
closest = inp; | |
} | |
}); | |
return closest; | |
}; | |
} | |
export function reverseFormula(formula) { | |
let rev = formula[REV_FORM]; | |
if (!rev) { | |
rev = createReverseFormula(formula); | |
formula[REV_FORM] = rev; | |
} | |
return rev; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment