$30 off During Our Annual Pro Sale. View Details »

Functional Reactive Programming with BaconJS

Functional Reactive Programming with BaconJS

See https://speakerdeck.com/tomkr/functional-reactive-programming-in-bacon-dot-js for a slightly updated version

An introduction to the concepts of functional reactive programming, using BaconJS as a library. Given as a lightning talk at Brightin HQ. Includes a bunch of code samples.

Tom Kruijsen

August 19, 2015
Tweet

More Decks by Tom Kruijsen

Other Decks in Programming

Transcript

  1. Functional reactive
    programming with
    Bacon.js
    Lightning Talk 2015-08-19
    Tom Kruijsen

    View Slide

  2. View Slide

  3. View Slide

  4. Functional Reactive
    Programming

    View Slide

  5. Event Streams as first
    class citizens

    View Slide

  6. Time

    View Slide

  7. User input

    View Slide

  8. AJAX

    View Slide

  9. Websockets

    View Slide

  10. 1 2 3 4
    Event stream

    View Slide

  11. 1 2 3 4
    map()
    3 6 9 12
    stream.map(x => x * 3)

    View Slide

  12. 1 3
    merge()
    stream1.merge(stream2)
    2 4
    1 2 3 4

    View Slide

  13. 1 3
    concat()
    stream1.concat(stream2)
    2 4
    1 3 4

    View Slide

  14. var up = $('#up').asEventStream('click');
    var down = $('#down').asEventStream('click');
    var counter =
    // map up to 1, down to -1
    up.map(1).merge(down.map(-1))
    // accumulate sum
    .scan(0, function(x,y) { return x + y });

    View Slide

  15. $('#once').asEventStream('click')
    .map('Clicked once.').first().log();
    $('#twice').asEventStream('click')
    .map('Clicked.').take(2).log();
    var first = $(‘#first’).asEventStream('click')
    .map('First.').first();
    var second = $(‘#second’).asEventStream('click')
    .map('Second.').first();
    first.concat(second).log();

    View Slide

  16. Streams can have
    side effects

    View Slide

  17. var firstname = $("#firstname").asEventStream("keyup")
    .map(function(event) {
    return $(event.target).val();
    }).toProperty("");
    var lastname = $("#lastname").asEventStream("keyup")
    .map(function(event) {
    return $(event.target).val();
    }).toProperty("");
    function nonEmpty(x) { return x.length > 0 };
    var valid = firstname.map(nonEmpty).and(lastname.map(nonEmpty));
    valid.onValue(function(enabled) {
    $("#submit").attr("disabled", !enabled);
    });

    View Slide

  18. AJAX

    View Slide

  19. res
    AJAX

    View Slide

  20. 1 2 3
    map() AJAX?
    res
    res
    res
    res
    res
    res

    View Slide

  21. 1 2 3
    map() AJAX!!!
    res
    res
    res
    res
    res
    res

    View Slide

  22. 1 2 3 4
    flatmap()
    res
    res
    res
    res
    res

    View Slide

  23. Functional reactive
    programming with
    Bacon.js
    Lightning Talk 2015-08-19
    Tom Kruijsen

    View Slide