2016年9月26日月曜日

開発環境

Eloquent JavaScript(Marijn Haverbeke 著、No Starch Press)のPart 1(Language)、Chapter 8(Bugs and Error Handling)、Exercises(Retry, The Locked Box)を取り組んでみる。

Exercises(Retry, The Locked Box)

コード(Emacs)

JavaScript

(() => {
    'use strict';
    var box,
        nums = [1,2,3,4,5],
        primitiveMultiply,
        retry,
        withBoxUnlocked,
        func;

    primitiveMultiply = (x, y) => {
        if (Math.random() < 0.5) {
            return x * y;
        }
        throw {
            name: 'primitiveMultiplyError',
            message: 'MultiplicatorUnitFilure',
        };
    };
    retry = (x, y) => {
        try {
            return primitiveMultiply(x, y);
        } catch (e) {
            return retry(x, y);
        }
    };
    nums.forEach(
        (x) => nums.forEach(
            (y) => console.log(`${x} x ${y} = ${retry(x, y)}`)))
    box = {
        locked: true,
        unlock: () => this.locked = false,
        lock: () => this.locked = true,
        _content: [],
        get content() {
            if (this.locked) {
                throw new Error('Locked!');
            }
            return this._content;
        }
    };
    withBoxUnlocked = (func) => {
        try {
            box.unlock();
            func();
        } catch (e) {
            console.log(e.name, e.message);
        } finally {
            box.lock();
        }
    };
    func = () => {
        throw {
            name: 'Error',
            message: 'message'
        };
    };
    console.log('locked', box.locked)
    withBoxUnlocked(func);
    console.log('locked', box.locked)
    box.lock();
    console.log('locked', box.locked)
    withBoxUnlocked(func);
    console.log('locked', box.locked)
})();

入出力結果(Terminal, Node.js)

$ node sample1.js
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
locked true
Error message
locked true
locked true
Error message
locked true
$

0 コメント:

コメントを投稿