開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Node.js, Safari(JavaScript エンジン)
- Learning JavaScript [邦訳](参考書籍)
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)の Random Words、Exercise: 6.を JavaScript で取り組んでみる。
Exercise: 6.
コード(Emacs)
HTML5
<pre id="output0"></pre> <input id="file0" type="file"> <button id="run0">run</button> <button id="clear0">clear</button> <script src="sample6.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(), emma = {}; 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+/); }; Array.prototype.pick = function (n) { let result = [], a = this.slice(); range(0, n).forEach( () =>result.push(a.splice(Math.floor(Math.random() * a.length), 1)) ); return result; }; reader.onload = () => { reader.result .split('\n') .map((line) => line.trim()) .filter((line) => line !== '') .forEach((line) => { let words = processLine(line) if (words) { words.forEach((word) => { if (emma[word]) { emma[word] += 1; } else { emma[word] = 1; } }); } }); output(); }; input_file0.onchange = () => reader.readAsText(input_file0.files[0]); let output = () => { let words = Object.keys(emma); if (words.length !== 0) { range(0, 5).forEach(() => p(words.pick(10))); words.pick(10).forEach((word) => p(word)); p('keys'); Object.keys(emma).pick(10).forEach((key) => p(key)); p('values'); Object.values(emma).pick(10).forEach((val) => p(val)); p('key, value'); Object.keys(emma).pick(10).forEach((key) => p(`${key}: ${emma[key]}`)); } }; let clear = () => pre0.textContent = ''; btn0.onclick = output; btn1.onclick = clear; output();
0 コメント:
コメントを投稿