stupidly golfed:
calc_type=(a,b,c)=>[...'+-*/'].find(x=>eval(a+x+b+'=='+c))
reasonable:
const ops = '+-*/'.split('').map(x => [x, new Function('a', 'b', 'c', `return (a ${x} b) === c`)]) const calc_type = (a, b, c) => ops.find(([x,f]) => f(a,b,c))?.[0]
optimized:
function calc_type(a, b, c) { switch (c) { case a + b: return '+' case a - b: return '-' case a * b: return '*' case a / b: return '/' } }
Guess what, flow control is expensive! Inlining saves the day, and case is number one.
case
Both of these are slower, despite not having to calculate the "expensive" division operation:
const ops = [ (a, b) => a + b, (a, b) => a - b, (a, b) => a * b, (a, b) => a / b, ] const calc_type = (a, b, c) => strs[ops.findIndex(f => f(a, b) === c)]
const ops = [ (a, b, c) => (a + b) === c, (a, b, c) => (a - b) === c, (a, b, c) => (a * b) === c, (a, b, c) => (a / b) === c, ] const calc_type = (a, b, c) => strs[ops.findIndex(f => f(a, b, c))]
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
JavaScript
stupidly golfed:
reasonable:
optimized:
Guess what, flow control is expensive! Inlining saves the day, and
case
is number one.Both of these are slower, despite not having to calculate the "expensive" division operation: