Skip to content

Instantly share code, notes, and snippets.

@FernandoBasso
Last active July 3, 2018 16:12
Show Gist options
  • Save FernandoBasso/709120ee1137aaafd706678f14ed1dfd to your computer and use it in GitHub Desktop.
Save FernandoBasso/709120ee1137aaafd706678f14ed1dfd to your computer and use it in GitHub Desktop.

Revisions

  1. FernandoBasso revised this gist Jul 3, 2018. 1 changed file with 19 additions and 1 deletion.
    20 changes: 19 additions & 1 deletion examples-map-filter-reduce.js
    Original file line number Diff line number Diff line change
    @@ -14,6 +14,7 @@ p(evens);


    ////////////////////////////////////////////////////////////////////////////////
    // filter urls with a certain characteristic ///////////////////////////////////
    /*
    <ul>
    <li><a href="https://theforce.io">Home page</a></li>
    @@ -23,4 +24,21 @@ p(evens);
    </ul>
    */

    all_links = [...document.querySelectorAll('.example-links a')];
    //
    // querySelectorAll returns a node list, not an array. We need an array
    // so we can use `filter`. Therefore, we use this little rest parameter
    // trick so `all_links` is an array.
    //
    const all_links = [...document.querySelectorAll('.example-links a')];

    //
    // Let's filter out (exclude) non-https links.
    //
    const https_only = all_links.filter(link => /^https:/.test(link.href));
    p(https_only.length);
    // → 2
    p(https_only[0].href);
    // → "https://theforce.io/"
    p(https_only[1].href);
    // → "https://theforce.io/about"

  2. FernandoBasso created this gist Jul 3, 2018.
    26 changes: 26 additions & 0 deletions examples-map-filter-reduce.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    const p = console.log.bind(console);


    ///////////////////////////////////////////////////////////////////////////////
    let nums = [3, 12, 21, 27, 44];

    let odds = nums.filter(num => num % 2 != 0);
    p(odds);
    // → [ 3, 21, 27 ]

    let evens = nums.filter(num => num % 2 == 0);
    p(evens);
    // [ 12, 44 ]


    ////////////////////////////////////////////////////////////////////////////////
    /*
    <ul>
    <li><a href="https://theforce.io">Home page</a></li>
    <li><a href="http://theforce.io">Home page</a></li>
    <li><a href="https://theforce.io/about">About</a></li>
    <li><a href="http://theforce.io/about">About</a></li>
    </ul>
    */

    all_links = [...document.querySelectorAll('.example-links a')];