2017年5月11日木曜日

開発環境

Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)の Part 1(Starting with the basics)、Chapter 9(Arrays and Lists)の Exercise: Other Ways to Modify an Array.を JavaScript で取り組んでみる。

Exercise: Other Ways to Modify an Array.

コード(Emacs)

HTML5

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

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

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    p = (x) => pre0.textContent += x + '\n',
    range = (start, end, step=1) => {
        let result = [];

        for (let i = start; i < end; i += 1) {
            result.push(i);
        }
        return result;
    };

let pop = (ary) => ary.splice(ary.length - 1, 1);
let unshift = (ary, item) => {
    ary.splice(0, 0, item);
    return ary.length;
};
let push = (ary, item) => {
    ary[ary.length] = item;
    return ary.length;
};
let myDelete = (ary, index) => {
    ary[index] = undefined;
    return true;
};

let output = () => {
    let ary1 = range(1, 11),
        ary2 = range(1, 11);

    p(ary1);
    p(ary2);

    p('pop');
    p(ary1.pop());
    p(ary1);
    p(pop(ary2));
    p(ary2);

    p('unshift');
    p(ary1.unshift(0));
    p(ary1);
    p(unshift(ary2, 0));
    p(ary2);

    p('push');
    p(ary1.push(10));
    p(ary1);
    p(push(ary2, 10));
    p(ary2);

    p('delete');
    p(delete ary1[2]);
    p(ary1);
    p(ary1[2] === undefined);
    p(ary1[2] === null);
    p(myDelete(ary2, 2));
    p(ary2);
    p(ary2[2] === undefined);
    p(ary2[2] === null);
};

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

output();













						

0 コメント:

コメントを投稿