2017年4月23日日曜日

開発環境

メタプログラミングRuby 第2版(Paolo Perrotta (著)、角 征典 (翻訳)、オライリージャパン)の1部(メタプログラミング Ruby)、4章(水曜日: ブロック)、4.5(呼び出し可能オブジェクト)、4.5.1(Proc オブジェクト)、&修飾、HighLine の例を JavaScript で取り組んでみる。

HTML5

<pre id="output0"></pre>
<button id="run0">run</button>
<button id="clear0">clear</button>

<script src="sample3.js"></script>

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    p = (x) => pre0.textContent += x + '\n';

let Proc = (fn) => {
    let that = {},
        call = (...args) => fn(...args);

    that.call = call;

    return that;
};
let Lambda = (fn) => {
    let that = {},
        call = (...args) => fn(...args);

    that.call = call;

    return that;
};

let math = (a, b, fn) => fn(a, b),
    doMath = (a, b, operation) => math(a, b, operation);

let myMethod = (theProc) => {
    return {call: (...args) => theProc(...args)};
};
let myMethod1 = (greeting, fn) => `${greeting}, ${fn()}!`;

let HighLine = () => {
    let that = {},
        ask = (n, msg, fn) => {
            p(msg);
            let inputs;
            if (n === 1) {
                inputs = 'Ivana, Roberto, Olaf';
            } else if (n === 2) {
                inputs = 'Bill';
            }
            return fn(inputs);
        };

    that.ask = ask;

    return that;
};
let output = () => {
    p('4.5.1 Proc オブジェクト');
    
    let inc = Proc((x) => x + 1);
    p(inc.call(2));
    
    let dec = Lambda((x) => x - 1);
    p(dec.call(2));

    let proc = {call: (x) => x + 1};
    p(proc.call(2));

    p('&修飾');
    p(doMath(2, 3, (x, y) => x * y));
    let p0 = myMethod((name) => `Hello, ${name}!`);
    p(p0.call('Bill'));

    let myProc = () => 'Bill';
    p(myMethod1('Hello', myProc));

    p('HighLine の例');
    let hl = HighLine(),
        friends = hl.ask(1, '友達を入力してください', (s) => s.split(','));
    p(`友達一覧: ${friends}(Array.isArray: ${Array.isArray(friends)})`);
    
    let name = hl.ask(2, '名前は?',
                      (s) => s[0].toUpperCase() + s.substring(1).toLowerCase());
    p(`Hello, ${name}`);
    
};

btn0.onclick = output;
btn1.onclick = () => pre0.textContent = '';

output();




  









						

0 コメント:

コメントを投稿