DEV Community

Harrison Reid
Harrison Reid

Posted on

Weird JS Challenge - Build this API

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 😛

Top comments (3)

Collapse
 
hongkongnoit profile image
等投胎窮三代IT狗

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');

})();
Collapse
 
harrison_codes profile image
Harrison Reid

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

Collapse
 
hongkongnoit profile image
等投胎窮三代IT狗

How do you make it without writing like this? :)