Home > database >  Typescript AddOrSubtract functions quiz
Typescript AddOrSubtract functions quiz

Time:10-21

New to learning typescript- trying to complete this problem from execute program:

Write a function that adds or subtracts 1 from a number. Argument 1 is the number. Argument 2 is a boolean. When it's true, add; otherwise, subtract.

Have tried many variations of the following:

function addOrSubtract(x: number, y: boolean): any {
  if (y = true) {
    return x 1;
  } else {
    return x-1;
  }
  return x;
}
addOrSubtract(5, true);
addOrSubtract(5, false);

The issue i am having is the test is only picking up the first condition. Specifying when y is false with an else if (y = false) statement gives me the same results.

Four tests results: addOrSubtract(5, true); Expected: 6 OK! addOrSubtract(5, false); Expected: 4 but got: 6 addOrSubtract('5', true); Expected: type error OK! addOrSubtract('5', null); Expected: type error OK!

Thanks in advance

CodePudding user response:

Your if condition is wrong. You are using assignment operator =. For comparison, you have to use equality check operator ==.

Below is the correct code -

function addOrSubtract(x: number, y: boolean): any {
  if (y == true) {
    return x 1;
  } else {
    return x-1;
  }
  return x;
}

Also since the variable y is of boolean type so you can use it directly in the if condition.

function addOrSubtract(x: number, y: boolean): any {
  if (y) {
    return x 1;
  } else {
    return x-1;
  }
  return x;
}

CodePudding user response:

To add on to Aman's answer, you can simplify this further using ternary statements.

function addOrSubtract(x: number, y: boolean): number {
  x = y ? x   1 : x - 1;
  return x;
}

Ternary statements are a really helpful thing in TypeScript and JavaScript, and can save you a lot of time if you know how to use them. Unless you are paid by the line.

Alternateively, in TypeScript especially it is better to use === instead of == as === strictly checks types when comparing as well.

  • Related