Skip to content

Instantly share code, notes, and snippets.

@luijar
Last active June 2, 2024 12:33
Show Gist options
  • Save luijar/ce6b96f13e31cb153093 to your computer and use it in GitHub Desktop.
Save luijar/ce6b96f13e31cb153093 to your computer and use it in GitHub Desktop.

Revisions

  1. luijar revised this gist Sep 19, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion ch01-magic-run.js
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,7 @@
    /*
    * Functional Programming in JavaScript
    * Chapter 01
    * Magical -run- function
    * Magical -run- function in support of Listing 1.1
    * Author: Luis Atencio
    */
    // -run- with two functions
  2. luijar created this gist Sep 19, 2015.
    31 changes: 31 additions & 0 deletions ch01-magic-run.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    /*
    * Functional Programming in JavaScript
    * Chapter 01
    * Magical -run- function
    * Author: Luis Atencio
    */
    // -run- with two functions
    var run2 = function(f, g) {
    return function(x) {
    return f(g(x));
    };
    };

    // -run- with three functions
    var run3 = function(f, g, h) {
    return function(x) {
    return f(g(h(x)));
    };
    };

    // Test this magical function
    var add1 = function(x) {return x + 1;};
    var mult2 = function(x) {return x * 2;};
    var square = function(x) {return x * x;};
    var negate = function(x) {return -x;};

    var double = run2(add1, add1);
    console.log(double(2)); //-> 4

    var testRun = run3(negate, square, mult2);
    console.log(testRun(2)); //->-16