DEV Community

Discussion on: Weird JS Challenge - Build this API

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? :)