2017年5月27日土曜日

開発環境

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 11(Case Study: Data Structure Selection)の Exercise: Sets, Bags, and Mixes.を JavaScript で取り組んでみる。

Exercise: Sets, Bags, and Mixes.

コード(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="sample03.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'),
    inputs = [input_file0, input_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;
    };

// es6には Set があるけど、Object で
let reader0 = new FileReader(),
    reader1 = new FileReader(),
    emma = {},
    words = {};

let skip = true;
let processLine = (line) => {
    if (line.indexOf('*** START OF THIS PROJECT GUTENBERG EBOOK EMMA ***') !== -1) {
        skip = false;
        return;
    }
    if (skip) {
        return;
    }
    line = line.replace(/[-'/]/g, ' ')
        .replace(/[;:,!?.()"_`”‘“’]/g, '')
        .toLowerCase();
    
    return line.split(/\s+/);
};
reader0.onload = () => {
    let lines =
        reader0.result
        .split('\n')
        .map((line) => line.trim())
        .filter((line) => line !== '');

    lines.forEach((line) => {
        let words =  processLine(line)
        if (words) {
            words.forEach((word) => emma[word] = 1);
        }
    });
    output();
    skip = false;
};
reader1.onload = () => {
    reader1.result
        .split('\n')
        .map((word) => word.trim())
        .filter((word) => word !== '')
        .forEach((word) => words[word] = 1);
    output();
};

let output = () => {
    if (Object.keys(emma).length !== 0 &&
        Object.keys(words).length !== 0) {
        p(
            Object.keys(emma)
                .filter((word) => !words[word])
                .slice(0, 100)
                .join('\n')
        );
    }
};

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

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

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

output();
















						

0 コメント:

コメントを投稿