DEV Community

loading...

Discussion on: Daily Challenge #312 - Describe the Function

Collapse
qm3ster profile image
Mihail Malo • Edited

JavaScript

stupidly golfed:

calc_type=(a,b,c)=>[...'+-*/'].find(x=>eval(a+x+b+'=='+c))
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

optimized:

const strs = ['+', '-', '*', '/']
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))]
Enter fullscreen mode Exit fullscreen mode