DEV Community

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:

function calc_type(a, b, c) {
  switch (c) {
    case a + b: return '+'
    case a - b: return '-'
    case a * b: return '*'
    case a / b: return '/'
  }
}
Enter fullscreen mode Exit fullscreen mode

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:

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