開発環境
- 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 10(Hashes)の Exercise: 10-3、10-4.を JavaScript で取り組んでみる。
Exercise: 10-3、10-4.
コード(Emacs)
HTML5
<pre id="output0"></pre> <input id="file0" type="file"> <button id="run0">run</button> <button id="clear0">clear</button> <script src="sample3.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 hasDuplicates = (ary) => { let o = {}; for (let i = 0, max = ary.length; i < max; i += 1) { if (o[ary[i]]) { return true; } o[ary[i]] = 1; } return false; }; let rotateLetter = (letter, n) => { n %= 26; n += n < 0 ? 26 : 0; let o = letter.codePointAt(0) + n; if (/[a-z]/.test(letter)) { return String.fromCodePoint(o - ('z'.codePointAt(0) < o ? 26 : 0)); } if (/[A-Z]/.test(letter)) { return String.fromCodePoint(o - ('Z'.codePointAt(0) < o ? 26 : 0)); } return letter; }; let rotateWord = (word, n) => word.split('') .map((c) => rotateLetter(c, n)) .join(''); let reader = new FileReader(); reader.onload = () => { let words = reader.result .split('\n') .filter((word) => word !== '') .map((word) => word.trim()); let wordsObj = {}; words.forEach((word) => wordsObj[word] = 1); Object.keys(wordsObj) .sort() .forEach((word) => { range(1, 26).forEach((n) => { let word0 = rotateWord(word, n); if (word < word0 && wordsObj[word0]) { p(`${word}, ${word0}, ${n}`); } }); }); }; input_file0.onchange = () => { p('4.'); reader.readAsText(input_file0.files[0]); }; let output = () => { p('3.'); let nums1 = [1, 2, 3, 4, 5], nums2 = [1, 2, 1, 4, 5]; p(hasDuplicates(nums1)); p(hasDuplicates(nums2)); }; let clear = () => pre0.textContent = ''; btn0.onclick = output; btn1.onclick = clear; output();
0 コメント:
コメントを投稿