2017年5月21日日曜日

開発環境

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 10(Hashes)の Exercise: 10-5.を JavaScript で取り組んでみる。

Exercise: 10-5.

コード(Emacs)

HTML5

<pre id="output0"></pre>
<input id="file0" type="file">
<input id="file1" type="file">

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

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

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    input_file0 = document.querySelector('#file0'),
    input_file1 = document.querySelector('#file1'),
    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 reader0 = new FileReader(),
    reader1 = new FileReader(),
    cmuObj = {},
    wordsObj = {};

reader0.onload = () => {
    reader0.result
        .split('\n')
        .filter((line) => line !== '')
        .map((line) => line.trim())
        .forEach((line) => {
            let [k, v] = line.split('  ');
            cmuObj[k.toLowerCase()] = v;
        });
    output();
};

reader1.onload = () => {
    reader1.result
        .split('\n')
        .filter((word) => word !== '')
        .map((word) => word.trim())
        .forEach((word) => wordsObj[word] = 1);
    output();
};

input_file0.onchange = () => {
    reader0.readAsText(input_file0.files[0]);
};
input_file1.onchange = () => {
    reader1.readAsText(input_file1.files[0]);
};

let output = () => {
    if (cmuObj && wordsObj) {
        Object.keys(wordsObj)
            .forEach((word) => {
                let cmu = cmuObj[word];
                if (cmu) {
                    let word1 = word.substring(1);
                    if (wordsObj[word1]) {
                        let cmu1 = cmuObj[word1];
                        if (cmu1 && cmu1 === cmu) {
                            let word2 = word[0] + word.substring(2);
                            if (wordsObj[word2]) {
                                let cmu2 = cmuObj[word2];
                                if (cmu2 && cmu2 === cmu) {
                                    p(`${word}, ${word1}, ${word2}`);
                                }
                            }
                        }
                    }
                }
            });
    }
};

let clear = () => pre0.textContent = '';

btn0.onclick = output;
btn1.onclick = clear;

output();
















						

0 コメント:

コメントを投稿