2017年5月17日水曜日

開発環境

Head First JavaScript Programming (Eric T. Freeman (著)、Elisabeth Robson (著)、O'Reilly Media)の Chapter 10.(Liberated functions - First Class Functions)の EXERCISE(No. 6886)を取り組んでみる。

EXERCISE(No. 6886)

コード(Emacs)

HTML5

<pre id="output0"></pre>
<button id="run0">run</button>
<button id="clear0">clear</button>
<script src="sample7.js"></script>

JavaScript

let 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 += 1) {
            result.push(i);
        }
        return result;
    };

let products = [
    {name: 'Grapefruit', calories: 170, color: 'red', sold:8200},
    {name: 'Orange', calories: 160, color: 'orange', sold: 12101},
    {name: 'Cola', calories: 210, color: 'caramel', sold: 25412},
    {name: 'Diet Cola', calories: 0, color: 'caramel', sold: 43922},
    {name: 'Lemon', calories: 200, color: 'clear', sold: 14983},
    {name: 'Raspberry', calories: 180, color: 'pink', sold: 9427},
    {name: 'Root Beer', calories: 200, color: 'caramel', sold: 9909},
    {name: 'Water', calories: 0, color: 'clear', sold: 62123},
];

let printProducts = (products) => {
    products.forEach((product) => {
        p(`Name: ${product.name}, Calories: ${product.calories}, ` +
          `Color: ${product.color}, Sold: ${product.sold}`);
    });
};

let compareName = (colaA, colaB) =>
    colaA.name < colaB.name ? -1 :
    colaA.name === colaB.name ? 0: 1;

let compareCalories = (colaA, colaB) =>
    colaA.calories < colaB.calories ? -1 :
    colaA.calories === colaB.calories ? 0: 1;

let compareColor = (colaA, colaB) =>
    colaA.color < colaB.color ? -1 :
    colaA.color === colaB.color ? 0: 1;

let output = () => {
    products.sort(compareName);
    p('Products sorted by name:');
    printProducts(products);

    products.sort(compareCalories);
    p('Products sorted by calories:');
    printProducts(products);

    products.sort(compareColor);
    p('Products sorted by color:');
    printProducts(products);
    
};

let clear = () => pre0.textContent = '';

btn0.onclick = output;
btn1.onclick = clear;

output();





    







						

0 コメント:

コメントを投稿

Comments on Google+: