2017年5月31日水曜日

開発環境

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)の Exrcises: Huffman Coding、The Frequency Table、Exercise: 11-8.を JavaScript で取り組んでみる。

Exercise: 6.

2147-0.txt

コード(Emacs)

HTML5

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

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

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

JavaScript

let btn0 = document.querySelector('#run0'),
    btn1 = document.querySelector('#clear0'),
    pre0 = document.querySelector('#output0'),
    input_file0 = document.querySelector('#file0'),
    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 reader = new FileReader(),
    frequency = {};

reader.onload = () => {
    range('a'.codePointAt(0), 'z'.codePointAt(0) + 1)
        .forEach((n) => frequency[String.fromCodePoint(n)] = 0);

    reader.result
        .split('')
        .filter((c) => /[a-zA-Z]/.test(c))
        .map((c) => c.toLowerCase())
        .forEach((c) => {
            frequency[c] += 1;
        });

    p(
        Object.keys(frequency)
            .sort()
            .map((c) => `${c}: ${frequency[c]}`)
            .join('\n')
    );
};

input_file0.onchange = () => reader.readAsText(input_file0.files[0]);

let output = () => {};
let clear = () => pre0.textContent = '';

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

output();















						

0 コメント:

コメントを投稿