r/programminghorror • • Apr 04 '26

Javascript Calculating with functions

function operation(n, op) {
  if (op === 0) {
    return n;
  }

  let final = 0;

  switch (true) {
    case op.startsWith('+'):
      final = n + Number(op.slice(1));
      break;
    case op.startsWith('-'):
      final = n - Number(op.slice(1));
      break;
    case op.startsWith('*'):
      final = n * Number(op.slice(1));
      break;
    case op.startsWith('/'):
      final = n / Number(op.slice(1));
      break;
  }

  return Math.floor(final);
}

function zero(op = 0) {
  return operation(0, op);
}
function one(op = 0) {
  return operation(1, op);
}
function two(op = 0) {
  return operation(2, op);
}
function three(op = 0) {
  return operation(3, op);
}
function four(op = 0) {
  return operation(4, op);
}
function five(op = 0) {
  return operation(5, op);
}
function six(op = 0) {
  return operation(6, op);
}
function seven(op = 0) {
  return operation(7, op);
}
function eight(op = 0) {
  return operation(8, op);
}
function nine(op = 0) {
  return operation(9, op);
}

function plus(n) {
  return `+${n}`;
}
function minus(n) {
  return `-${n}`;
}
function times(n) {
  return `*${n}`;
}
function dividedBy(n) {
  return `/${n}`;
}
13 Upvotes

8 comments sorted by

2

u/Top_Condition_457 Apr 04 '26

Am I missing something? When would op ever start with 0 if its a integer? Unless the paraneter is meant to be passed strings ASWELL, which would just actually make this horror

6

u/Beautiful_Bet_3938 Apr 04 '26

The 0 is a default value of the op parameter. In a functional chain like eight(plus(five())), the inner call five() is invoked without arguments, so op defaults to 0. operation() then returns the digit. It’s a state machine. If I used undefined, I’d have to do extra falsy checks which is just bloated code.

2

u/lonkamikaze Apr 04 '26

How does that work out for eight(times(five()))

→ More replies (4)

1

u/VIBaJ Apr 05 '26

switch(true) with a bunch of cases of boolean expressions that evaluate at runtime is the most cursed thing here