2017年4月24日月曜日

JavaScript - Starting with the basics - Fruitful Subroutines(Compare)

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 4(Fruitful Subroutines)のExercises(Compare).を JavaScript で取り組んでみる。

Exercises(Compare).

コード(Emacs)

HTML5

```<pre id="output0"></pre>
x = <input id="x0" type="number" value="5">
y = <input id="y0" type="number" value="10">
<br>
<button id="run0">run</button>
<button id="clear0">clear</button>

<script src="sample_compare.js"></script>
```

JavaScript

```let input_x = document.querySelector('#x0'),
input_y = document.querySelector('#y0'),
inputs = [input_x, input_y],
btn0 = document.querySelector('#run0'),
btn1 = document.querySelector('#clear0'),
pre0 = document.querySelector('#output0'),
p = (x) => pre0.textContent += x + '\n',
range = (start, end, step=1) => {
let result = [];
for (let i = start; i < end; i += step) {
result.push(i);
}
return result;
};

let compare = (x, y) => {
if (x > y) {
return 1;
}
if (x === y) {
return 0;
}
return -1;
};

let output = () => {
pre0.textContent = '';
range(1, 11).forEach((x) => {
range(1, 11).forEach((y) => {
p(`compare(\${x}, \${y}) => \${compare(x, y)}`);
})
});

let [x, y] = inputs.map((input) => parseInt(input.value, 10));

p(`compare(\${x}, \${y}) => \${compare(x, y)}`);
};

inputs.forEach((input) => input.onchange = output);
btn0.onclick = output;
btn1.onclick = () => pre0.textContent = '';

output();
```

x =
y =