Skip to content

Instantly share code, notes, and snippets.

@MrTelanie
Created August 18, 2019 10:38
Show Gist options
  • Save MrTelanie/f20beaec02ddeb2ad29bde76d037177f to your computer and use it in GitHub Desktop.
Save MrTelanie/f20beaec02ddeb2ad29bde76d037177f to your computer and use it in GitHub Desktop.
reverse a function
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