Start learning free

LESSON 89 OF 348 · CONDITIONAL STATEMENTS - CHALLENGES

Absolute Difference in TypeScript: Subtract Smaller from Larger

Practice Read the full explanation

The absolute difference is a measure of the difference between two numbers but expressed as a positive number.

In other words, it’s taking the difference between two values (x - y) and then calculating the absolute value of the result.

Create a function that takes in two numbers a and b and returns their absolute difference.

Examples:

absDiff(3, 0) ➞ 3

absDiff(0, 3) ➞ 3

absDiff(10, -1) ➞ 11

absDiff(-5, -7) ➞ 2

absDiff(6, -6) ➞ 12

absDiff(1.5, 1.5) ➞ 0

Note:

Do not use the abs() function provided by TypeScript (it will defeat the purpose of the challenge)


Hints:


If a is less then b, the absolute difference equals b - a. What if a is greater than or equal to b?

If a < b, we should return b - a. Otherwise, we should return a - b. We can use an if statement to put this in code.
STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Absolute Difference in TypeScript, explained

    Problem overview

    The method absDiff takes two numbers, a and b, and returns how far apart they are, as a number that is never negative. This is the absolute value of a - b. The built-in Math.abs is off limits, so the sign has to be handled by hand.

    Take absDiff(10, -1). The plain difference 10 - (-1) is 11, and that is the answer. For absDiff(0, 3) the plain difference 0 - 3 is -3, which is negative, so the answer is flipped to 3. For absDiff(-5, -7) the answer is 2, and for absDiff(1.5, 1.5) it is 0.

    Approach

    You could compute a - b and negate it when it is below zero, which is the same idea as the previous abs lesson. A shorter way is to decide up front which number is larger and subtract the smaller from it. A larger number minus a smaller number can't be negative.

    So there are two cases. If a is smaller than b, the answer is b - a. Otherwise a is greater than or equal to b, and the answer is a - b. When the numbers are equal, both formulas give 0, so it doesn't matter which side takes the tie.

    Step by step

    1. Write the test. Add an if with its closing brace whose condition is a < b.
    2. Return b - a inside it. When a is the smaller number, this subtraction is not negative.
    3. Return a - b after the if. No else is needed. If a < b was true, the method has already returned from inside the if, so this line is reached only when a is greater than or equal to b. In that case a - b is not negative.

    The solution in TypeScript

    class Solution {
        absDiff(a: number, b: number): number {
            if (a < b) {
                return b - a;
            }
            return a - b;
        }
    }
    

    Some details of the code:

    • An early return replaces else. A return ends the method immediately, so the code after the if acts as the "otherwise" branch. Many programmers prefer this shape because it keeps the code flat. Writing the else explicitly would behave identically.
    • The annotations are for the compiler. a: number, b: number and the return type : number vanish when tsc writes JavaScript, so nothing checks the arguments at run time.
    • Decimals work like integers. A number is a double-precision floating-point value, so the same code handles 1.5 and -7.

    Edge cases and common mistakes

    • Equal numbers. With a equal to b, the condition is false and the method returns a - b, which is 0. That is correct.
    • Negative inputs. Both numbers can be negative, as in absDiff(-5, -7). The code never assumes a sign: it compares the numbers and subtracts, and -5 - (-7) is 2.
    • Mixed signs. With absDiff(6, -6), a is not below b, so the result is 6 - (-6), which is 12. Subtracting a negative number adds its size.
    • Subtracting in a fixed order. Always returning a - b fails whenever a is smaller than b, because the answer comes out negative. The comparison is what fixes that.
    • Decimal rounding. Floating-point numbers are binary, so some decimals aren't exact. absDiff(0.3, 0.1) gives 0.19999999999999998, not 0.2. This is how all doubles behave and not a fault of the method. Avoid comparing such results with === against a decimal literal.
    • NaN. If either input is NaN, the comparison is false and the result is NaN.

    Testing

    These inputs cover each branch. Try them in the editor above:

    • absDiff(3, 0) should give 3, which takes the second return.
    • absDiff(0, 3) should give 3, which takes the first return.
    • absDiff(10, -1) should give 11.
    • absDiff(-5, -7) should give 2.
    • absDiff(1.5, 1.5) should give 0.

    The method makes one comparison and one subtraction, so it runs in constant time and uses constant space.

    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free