DEV Community

Discussion on: Daily Challenge #293 - Name the Operations

Collapse
 
willsmart profile image
willsmart

Just a quicky in JS

ops = [
  { name: 'subtraction', op: (a, b) => a - b },
  { name: 'addition', op: (a, b) => a + b },
  { name: 'multiplication', op: (a, b) => a * b },
  { name: 'division', op: (a, b) => a / b },
];

nameTheOps = s => {
  let [left, right, ...rest] = s.trim().split(/\s+/g);
  return rest
    .map(res => {
      const name = ops.find(({ op }) => op(+left, +right) == res)?.name ?? 'unknown op';
      left = right;
      right = res;
      return name;
    })
    .join(', ');
};

nameTheOps('9 4 5 20 25');
//> "subtraction, multiplication, addition"
Enter fullscreen mode Exit fullscreen mode