開発環境
- 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)の Constructing New Operators、Exercise: Constructing New Operators.を JavaScript で取り組んでみる。
Exercise: Constructing New Operators.
コード(Emacs)
HTML5
<pre id="output0"></pre> <label for="n0">n = </label> <input id="n0" type="number" min="0" step="1" value="20"> <button id="run0">run</button> <button id="clear0">clear</button> <script src="sample02.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'), btn1 = document.querySelector('#clear0'), pre0 = document.querySelector('#output0'), input_n = document.querySelector('#n0'), 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; }; // JavaScript では新しい演算子を定義する方法がないから、階乗を計算する関数を再帰とかいくつかの方法で定義してみる。 let factorial1 = (n) => n <= 1 ? 1 : n * factorial1(n - 1); let factorial2 = (n) => { let inner = (n, result) => { if (n === 0) { return result; } return inner(n - 1, n * result); }; return inner(n, 1); }; let factorial3 = (n) => range(1, n + 1).reduce((x, y) => x * y, 1), fns = [factorial1, factorial2, factorial3]; let output = () => { p( range(0, 11) .map((n) => fns .map((fn) => fn(n)) .join('\n')) .join('\n') ); let n = parseInt(input_n.value, 10); p(fns.map((fn) => fn(n)).join('\n')); }; let clear = () => pre0.textContent = ''; input_n.onchange = output; btn0.onclick = output; btn1.onclick = clear; output();
0 コメント:
コメントを投稿