Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Fungsional dengan JavaScript

Fungsional dengan JavaScript

https://www.meetup.com/lambdaindonesia/events/259616507/

Pening karena ingin mulai berpikir secara fungsional tapi bingung mau mulai dari mana? Jangan takut. Ternyata belajar pemrograman fungsional bisa diawali dengan berlatih lewat Javascript mengubah iterasi for/while menjadi penggunaan fungsi ordo-tinggi dari Array. Akan dikupas pemakaian Array secara tulen--berarti tanpa ada for/while--untuk mengimplementasikan algoritma dasar pencarian.

Ariya Hidayat

March 21, 2019
Tweet

More Decks by Ariya Hidayat

Other Decks in Programming

Transcript

  1. Fungsional dengan JavaScript

    View full-size slide

  2. https://twitter.com/fogus/status/297441838745395201

    View full-size slide

  3. Tanpa for/while!

    View full-size slide

  4. Fungsi Ordo Tinggi: map, reduce
    Barisan dan Faktorial
    Pencarian: every, some, reduce
    Pengurutan

    View full-size slide

  5. Array.prototype.map
    map calls callbackfn once for each element in
    the array, in ascending order, and constructs a
    new Array from the results.
    callbackfn is called with three arguments:
    ● the value of the element
    ● the index of the element, and
    ● the object being traversed.
    [ ... ].map(callbackfn)

    View full-size slide

  6. Contoh Array.prototype.map
    [1, 2, 3].map(function (x) {
    return x * x;
    });
    [1, 4, 9]
    [7, 7, 7].map(function (x, y) {
    return y;
    });
    [0, 1, 2]
    y = index
    x = element

    View full-size slide

  7. Array.prototype.reduce
    [ ... ].reduce(callbackfn, initial)
    callbackfn is called with four arguments:
    ● the previousValue (or value from the previous call
    to callbackfn),
    ● the currentValue (value of the current element)
    ● the currentIndex, and
    ● the object being traversed.

    View full-size slide

  8. Contoh Array.prototype.reduce
    [1, 2, 3, 4, 5].reduce(function (sum, i) {
    return sum + i;
    });
    [1, 2, 3, 4, 5].reduce(function (sum, i) {
    return sum + i;
    }, 100);
    15
    115
    [1, 2, 3].reduce(function(result, x) {
    return result.concat(x + 2);
    }, []);
    [3, 4, 5]

    View full-size slide

  9. Angka (untuk Barisan)
    var result = [];
    for (var i = 1; i < 4; ++i) result.push(i)
    console.log(result); // [1, 2, 3]

    View full-size slide

  10. Karakter (untuk String)
    var list = '';
    for (var i = 0; i < 26; ++i)
    list += String.fromCharCode(i + 65);
    console.log(list); // 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    View full-size slide

  11. var x = Array(3);
    Array-nya “kosong”
    x.length; 3
    console.log(x); []

    View full-size slide

  12. Operator in Section 11.8.7
    0 in Array(3); // false
    1 in Array(3); // false
    2 in Array(3); // false
    2 in [,,9]; // true
    toString relies on join (Section 15.4.4.5)
    join convertes undefined or null to an empty string

    View full-size slide

  13. var x = Array.apply(0, Array(3));
    console.log(x); [undefined, undefined, undefined]
    Array diisi dengan undefined

    View full-size slide

  14. Function.prototype.apply
    Math.max(14, 3, 77);
    Math.max.apply(Math, [14, 3, 77]);
    Array
    Parameters
    http://www.2ality.com/2011/08/spreading.html
    Section 15.3.4.3

    View full-size slide

  15. Misteri Array.apply
    Array.apply(0, Array(3));
    Array.apply(0, [,,]);
    Array(undefined, undefined, undefined);
    “ghost elements” got converted into undefined

    View full-size slide

  16. Barisan Aritmatika
    Array.apply(0, Array(3)).map(function (x, y) {
    return y + 1;
    }); [1, 2, 3]
    Array.apply(0, Array(3)).map(function (x, y) {
    return (y + 1) * (y + 1);
    });
    [1, 4, 9]
    Array.apply(0, Array(3))
    [undefined, undefined, undefined]

    View full-size slide

  17. Strings
    Array.apply(0, Array(26)).map(function(x,y) {
    return String.fromCharCode(y + 65);
    }).join('');

    View full-size slide

  18. ”Sequences using JavaScript Array”
    https://ariya.io/2013/07/sequences-using-javascript-array
    Lebih rinci

    View full-size slide

  19. Faktorial: Versi Loop
    function factorial(n) {
    var result = 1;
    for (var i = 1; i <= n; ++i) result *= i;
    return result;
    }
    factorial(5) 120
    1 * 2 * 3 * 4 * 5

    View full-size slide

  20. dengan Array.prototype.reduce
    function factorial(n) {
    return Array.apply(0, Array(n))
    .reduce(function(x, y, z) {
    return x + x * z;
    }, 1);
    }
    0..N-1
    Accumulate

    View full-size slide

  21. Faktorial dari 5
    x z
    1
    1 0
    2 1
    6 2
    24 3
    120 4
    x + x * z

    View full-size slide

  22. Bilangan Prima
    13? Iya
    15? Nggak

    View full-size slide

  23. function primeList(N) {
    return Array.apply(0, Array(N)).map(function (x, y) { return y }).
    filter(function (i) {
    return (i > 1) && Array.apply(0, Array(1 + ~~Math.sqrt(i))).
    every(function (x, y) { return (y < 2) || (i % y !== 0) });
    });
    }
    primeList(20) [ 2, 3, 5, 7, 11, 13, 17, 19 ]

    View full-size slide

  24. Kelinci Fibonacci
    0, 1, 1, 2, 3, 5, 8, 13, 21,...

    View full-size slide

  25. function fibo(n) {
    return Array.apply(0, Array(n)).reduce(function(x, y, z){
    return x.concat((z < 2) ? z : x[z-1] + x[z-2]);
    }, []);
    }
    [ 0, 1, 1, 2, 3, 5, 8, 13, 21 ]
    fibo(9)

    View full-size slide

  26. “Prime Numbers, Factorial, and Fibonacci Series
    with JavaScript Array”
    https://ariya.io/2013/07/prime-numbers-factorial-and-
    fibonacci-series-with-javascript-array
    Lebih rinci

    View full-size slide

  27. Cari String yang Terpanjang
    function findLongest(array) {
    for (var i = 0, longest = ''; i < array.length; ++i)
    if (array[i].length > longest.length)
    longest = array[i];
    return longest;
    }
    findLongest(['ab', 'abc', 'a']) 'abc'

    View full-size slide

  28. dengan Array.prototype.reduce
    function findLongest(array) {
    return array.reduce(function (longest, entry) {
    return entry.length > longest.length ? entry : longest;
    }, '' });
    }
    findLongest(['ab', 'abc', 'a']) 'abc'

    View full-size slide

  29. Reduce: Langkah demi Langkah
    entry entry.length longest longest.length
    '' 0
    'ab' 2 'ab' 2
    'abc' 3 'abc' 3
    'a' 1 'abc' 3

    View full-size slide

  30. Ambil juga Indeksnya
    function findLongest(array) {
    return array.reduce(function (longest, entry, index) {
    return entry.length > longest.value.length ?
    { index: index, value: entry } : longest;
    }, { index: -1, value: '' });
    }
    findLongest(['ab', 'abc', 'a']) { index: 1, value: 'abc' }

    View full-size slide

  31. Reduce: Langkah demi Langkah
    entry longest.index longest.value
    -1 ''
    'ab' 0 'ab'
    'abc' 1
    'abc'
    'a' 1
    'abc'

    View full-size slide

  32. “Searching using Array.prototype.reduce”
    https://ariya.io/2013/10/searching-using-array-prototype-reduce
    Lebih rinci

    View full-size slide

  33. Langkah demi Langkah
    14 3 19 77
    14 19 77 3
    19 77 3 14
    77 3 14 19
    3 14 19 77

    View full-size slide

  34. N Element = N Langkah
    Array.apply(0, Array(array.length)).map(function () {
    // Do something
    });
    0..N-1
    Inner loop

    View full-size slide

  35. Cari yang Terkecil
    function findSmallest(array) {
    return array.reduce(function (min, entry, index) {
    return min.value < entry ?
    { index: index, value: entry } : min;
    }, { value: null });
    }
    findSmallest([14, 3, 19, 77]) { index: 1, value: 3 }

    View full-size slide

  36. Ulangi N kali
    function sort(input) {
    var array = input.slice(0);
    return Array.apply(0, Array(array.length)).map(function () {
    return array.splice(findSmallest(array).index, 1).pop();
    });
    }
    Sebelum splice
    Sesudah splice
    [14, 3, 19, 77]
    [14, 19, 77]
    { index: 1, value: 3 }

    View full-size slide

  37. Implementasi Lengkap (8 Baris)
    function sort(input) {
    var array = input.slice(0);
    return Array.apply(0, Array(array.length)).map(function () {
    return array.splice(array.reduce(function (min, entry, index) {
    return min.value < entry ? min : index: index, value: entry };
    }).index, 1).pop();
    });
    }

    View full-size slide

  38. “Searching using Array.prototype.reduce”
    https://ariya.io/2013/10/searching-using-array-prototype-reduce
    Lebih Rinci

    View full-size slide

  39. “Sorting Networks using Higher-Order Functions
    of JavaScript Array”
    https://ariya.io/2013/10/sorting-networks-using-higher-order-functions-
    of-javascript-array
    Lebih Rinci

    View full-size slide

  40. Fungsi Ordo Tinggi: map, reduce
    Barisan dan Faktorial
    Pencarian: every, some, reduce
    Pengurutan

    View full-size slide

  41. Fungsional itu seru

    View full-size slide

  42. Terima Kasih
    Some artworks are from unsplash.com/ and openclipart.org.
    @ariya114

    View full-size slide