2016年9月15日木曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 7(Data Structures)、34(Employee List Removal)を取り組んでみる。

34(Employee List Removal)

コード(Emacs)

<div id="output0"></div>
<div id="error0"></div>
<script src="sample34.js"></script>
(function () {
    'use strict';
    var employees,
        i = 0,
        div_output = document.querySelector('#output0'),
        div_error = document.querySelector('#error0'),
        nl = '<br>',
        output,
        getIndex,
        remove;

    employees = ['John Smith',
                 'Jackie Jackson',
                 'Chris Jones',
                 'Amanda Cullen',
                 'Jeremy Goodwin'];

    output = function () {
        div_output.innerHTML +=
            'There are ' + employees.length + ' employees:' + nl +
            employees.join(nl) + nl + nl +
            '<label for="remove' + i + '">Enter an employee name to remove: ' +
            '</label>' +
            '<input id="remove' + i + '" type="text">' + nl + nl;
        getIndex();
    };
    getIndex = function () {
        var input_remove = document.querySelector('#remove' + i);
        
        console.log(input_remove);
        input_remove.onchange = function () {
            var name = input_remove.value,
                index = employees.indexOf(name);

            input_remove.setAttribute('value', name);
            input_remove.onchange = null;
            if (index === -1) {
                div_error.innerText = name + ' does not exist.';
                getIndex();
            } else {
                div_error.innerText = '';
                i += 1;
                remove(index);
            }
        };
    };
    remove = function (index) {
        employees.splice(index, 1);
        output();
    };

    output();
}());

0 コメント:

コメントを投稿