開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Node.js, Safari(JavaScript エンジン)
- Learning JavaScript [邦訳] (参考書籍)
Head First Python (Paul Barry (著)、O'Reilly Media)のChapter 13.(Advanced Iteration: Looping Like Crazy) の SHARPEN YOUR PENCIL(No. 8974) を JavaScript で取り組んでみる。
SHARPEN YOUR PENCIL(No. 8974)
コード(Emacs)
HTML5
<input id="file0" type="file"> <br> <button id="run0">run</button> <button id="clear0">clear</button> <pre id="output0"></pre> <script src="sample1.js"></script>
JavaScript
let input0 = document.querySelector('#file0'), btn0 = document.querySelector('#run0'), btn1 = document.querySelector('#clear0'), pre0 = document.querySelector('#output0'), p = (x) => pre0.textContent += x + '\n'; let po = (o) => { Object.keys(o).forEach((k) => { p(`${k}: ${o[k]}`); }); }; let convert2ampm = (s) => { let d = s.split(':'), h = parseInt(d[0], 10), m = parseInt(d[1], 10); let date = new Date(0, 0, 0, h, m), ts = date.toLocaleString(); ts = ts.split(', ')[1]; return ts.substring(ts, ts.length - 6) + ts.substring(ts.length - 2); }; let output = () => { let reader = new FileReader(); reader.onload = () => { let data = reader.result .split('\n') .slice(1) .map((x) => x.trim()) .filter((x) => x !== ''), flight = {}; data .map((x) => x.split(',')) .forEach((x) => { flight[x[0]] = x[1]; }); po(flight); p(''); let flight2 = {}; Object.keys(flight) .map((k) => flight2[convert2ampm(k)] = flight[k] .split(' ') .map((s) => s[0].toUpperCase() + s.substring(1).toLowerCase()) .join(' ')); po(flight2); }; reader.readAsText(input0.files[0]); }; btn0.onclick = output; btn1.onclick = () => { pre0.textContent = ''; }; output();
0 コメント:
コメントを投稿