2016年10月6日木曜日

開発環境

Exercises for Programmers: 57 Challenges to Develop Your Coding Skills (Brian P. Hogan 著、Pragmatic Bookshelf)のChapter 10(Full Programs)、53(Todo List)を取り組んでみる。

53(Todo List)

コード(Emacs)

HTML5

<button id="add0">追加</button>
<button id="show0">表示</button>
<div id="output0"></div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script src="sample53.js"></script>

JavaScript

{
    'use strict';
    let $div_output = $('#output0'),
        $button_add = $('#add0'),
        $button_show = $('#show0');

    const KEY = 'todo_list';

    let getTodoList = () => {
        let json = localStorage.getItem(KEY);

        return json === null ? [] : JSON.parse(json);    
    };
    let addTodo = (todo_list) => {
        let $input = $('<input>'),
            $br = $('<br>');

        $div_output.append($input).append($br);
        $input.focus();
        $input.keypress((e) => {
            if (e.keyCode === 13) {
                let val = $input.val();

                $input.attr({readOnly:true});
                if (val !== '') {
                    todo_list.push(val);            
                    addTodo(todo_list);
                } else {
                    let todo_list0 = getTodoList();                
                    todo_list0 = todo_list0.concat(todo_list);
                    localStorage.setItem(KEY, JSON.stringify(todo_list0));
                }
            }
        });
    };
    let showTodo = () => {
        let todo_list = getTodoList(),
            output = '';
        
        todo_list.forEach((todo, i) => {
            output += `${i + 1}: ${todo}<br>`;
        });
        $div_output.html(output);
        let $input = $(`<input id="remove0" type="number" min="1" ` +
                       `max="${todo_list.length -1}" step="1">`);
        let $label = $('<label>');
        $label.text('削除する項目番号: ');
        $label.attr({'for': 'remove0'});
        $div_output.append($label).append($input);
        $input.keypress((e) => {
            if (e.keyCode === 13) {
                let n = parseInt($input.val(), 10);

                if (!isNaN(n)) {
                    todo_list.splice(n - 1, 1);
                    localStorage.setItem(KEY, JSON.stringify(todo_list));
                    showTodo();
                }
            }
        });
    };
    $button_add.click((e) => {
        $div_output.html('');
        addTodo([])
    });
    $button_show.click(showTodo);
}

0 コメント:

コメントを投稿

Comments on Google+: