loading...

Weird JS Challenge - Build this API

harrison_codes profile image Harrison Reid ・1 min read

TIL about a JavaScript feature I'd never seen before. I've used it to create the (super basic) calculator API shown below.

The challenge, should you choose to accept it, is to recreate this (or a similar API) yourself. If you're anything like me, you'll learn a bunch!

// Using the calculator!

calculator.one.plus.two.plus.three.equals
=> 6

calculator.two.plus.four.plus.seven.plus.eight.equals
=> 21

Hint: The solution is not to just use a single object with heaps of very deeply nested properties 😛

Discussion

markdown guide
 

Hong Kong No IT (香港創科局高官二世祖圍威喂)

const calculator = (() => {

    const numbers = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];

    class Unit {
        constructor(num, type) {
            return numbers.reduce((acc, n, i) => ({
                ...acc,
                get [n]() {
                    switch (type) {
                        case 'PLUS':
                            return new Num(num + (i + 1));
                        case 'MINUS':
                            return new Num(num - (i + 1));
                        case 'MULTIPLY':
                            return new Num(num * (i + 1));
                        case 'DIVISION':
                            return new Num(num / (i + 1));
                    }
                }
            }), {});
        }
    }

    class Num {
        constructor(num) {
            this.num = num;
        }

        get equals() {
            return this.num;
        }

        get plus() {
            return new Unit(this.num, 'PLUS');
        }

        get minus() {
            return new Unit(this.num, 'MINUS');
        }

        get multipleTo() {
            return new Unit(this.num, 'MULTIPLY');
        }

        get dividedBy() {
            return new Unit(this.num, 'DIVISION');
        }

    }

    return new Unit(0, 'PLUS');

})();
 

Not how I did it, but works equally well! Loving it 👏