Skip to content

5. Extra: Exercises

Sjors Wijsman edited this page May 26, 2020 · 4 revisions

5.1 Exercise: Array Cardio Day 1 (JSBootcamp)

From: https://www.youtube.com/watch?v=HB1ZC7czKRs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Array Cardio 💪</title>
</head>
<body>
  <p><em>Psst: have a look at the JavaScript Console</em> 💁</p>
  <script>
    // Get your shorts on - this is an array workout!
    // ## Array Cardio Day 1

    // Some data we can work with
    const inventors = [
      { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
      { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
      { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
      { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
      { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
      { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
      { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
      { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
      { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
      { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
      { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
      { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
    ];

    const people = ['Beck, Glenn', 'Becker, Carl', 'Beckett, Samuel', 'Beddoes, Mick', 'Beecher, Henry', 'Beethoven, Ludwig', 'Begin, Menachem', 'Belloc, Hilaire', 'Bellow, Saul', 'Benchley, Robert', 'Benenson, Peter', 'Ben-Gurion, David', 'Benjamin, Walter', 'Benn, Tony', 'Bennington, Chester', 'Benson, Leana', 'Bent, Silas', 'Bentsen, Lloyd', 'Berger, Ric', 'Bergman, Ingmar', 'Berio, Luciano', 'Berle, Milton', 'Berlin, Irving', 'Berne, Eric', 'Bernhard, Sandra', 'Berra, Yogi', 'Berry, Halle', 'Berry, Wendell', 'Bethea, Erin', 'Bevan, Aneurin', 'Bevel, Ken', 'Biden, Joseph', 'Bierce, Ambrose', 'Biko, Steve', 'Billings, Josh', 'Biondo, Frank', 'Birrell, Augustine', 'Black, Elk', 'Blair, Robert', 'Blair, Tony', 'Blake, William'];

    let exercise;
    let results;


    // Array.prototype.filter()
    exercise = "Filter the list of inventors for those who were born in the 1500's"
    results = inventors.filter(inventor => inventor.year >= 1500 && inventor.year < 1600);

    console.log("%c" + exercise + ":", "color: white; font-size: large");
    console.table(results)


    // Array.prototype.map()
    exercise = "2. Give us an array of the inventors first and last names";
    results = inventors.map(inventor => inventor.first + " " + inventor.last)

    console.log("%c" + exercise + ":", "color: white; font-size: large");
    console.log(results)


    // Array.prototype.sort()
    exercise = "3. Sort the inventors by birthdate, oldest to youngest";
    results = inventors.sort(function(a, b) {
      return a.year - b.year;
    });

    console.log("%c" + exercise + ":", "color: white; font-size: large");
    console.table(results)


    // Array.prototype.reduce()
    exercise = "4. How many years did all the inventors live all together?";
    results = inventors.reduce((total, inventor) => total + (inventor.passed - inventor.year), 0);

    console.log("%c" + exercise + ":", "color: white; font-size: large");
    console.log(results)


    exercise = "5. Sort the inventors by years lived";
    results = inventors.sort(function(a, b) {
      return (a.passed - a.year) - (b.passed - b.year);
    });

    console.log("%c" + exercise + ":", "color: white; font-size: large");
    console.table(results)


    exercise = "6. create a list of Boulevards in Paris that contain 'de' anywhere in the name";
    // https://en.wikipedia.org/wiki/Category:Boulevards_in_Paris
    const boulevards = Array.from(document.querySelectorAll('.mw-category a')).map(boulevard => boulevard.textContent);
    if (boulevards) {
      results = boulevards.filter(boulevard => boulevard.includes("de"));
    }

    console.log("%c" + exercise + ":", "color: white; font-size: large");
    console.log(results)


    exercise = "7. Sort exercise: Sort the people alphabetically by last name";
    const splitNames = people.map(person => person.split(', '))
    results = splitNames.sort(function(a, b) {
      return a[0] > b[0] ? 1 : -1;
    })

    console.log("%c" + exercise + ":", "color: white; font-size: large");
    console.log(results);


    exercise = "8. Reduce exercise: Sum up the instances of each of these";
    const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck' ];
    results = data.reduce(function(result, instance) {
      if (!result[instance]) {
        result[instance] = 0;
      }
      result[instance]++;
      return result
    }, {});

    console.log("%c" + exercise + ":", "color: white; font-size: large");
    console.table(results)
  </script>
</body>
</html>

5.2 Exercise: Array Cardio Day 2 (JSBootcamp)

From: https://www.youtube.com/watch?v=QNmRfyNg1lw

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Array Cardio 💪💪</title>
</head>
<body>
  <p><em>Psst: have a look at the JavaScript Console</em> 💁</p>
  <script>
    // ## Array Cardio Day 2

    const people = [
      { name: 'Wes', year: 1988 },
      { name: 'Kait', year: 1986 },
      { name: 'Irv', year: 1970 },
      { name: 'Lux', year: 2015 }
    ];

    const comments = [
      { text: 'Love this!', id: 523423 },
      { text: 'Super good', id: 823423 },
      { text: 'You are the best', id: 2039842 },
      { text: 'Ramen is my fav food ever', id: 123523 },
      { text: 'Nice Nice Nice!', id: 542328 }
    ];

    let exercise = "";
    let result;

    // Some and Every Checks
    // Array.prototype.some()
    exercise = "Is at least one person 19 or older?";
    console.log("%c" + exercise + ":", "color: white; font-size: large");
    result = people.some(person => (2020 - person.year) > 19);
    console.log(result);

    // Array.prototype.every()
    exercise = "Is everyone 19 or older?";
    console.log("%c" + exercise + ":", "color: white; font-size: large");
    result = people.every(person => (2020 - person.year) > 19);
    console.log(result);

    // Array.prototype.find()
    // Find is like filter, but instead returns just the one you are looking for
    exercise = "Find the comment with the ID of 823423";
    console.log("%c" + exercise + ":", "color: white; font-size: large");
    result = comments.find(comment => comment.id === 823423)
    console.log(result);

    // Array.prototype.findIndex()
    exercise = "Find the comment with this ID";
    console.log("%c" + exercise + ":", "color: white; font-size: large");
    result = comments.findIndex(comment => comment.id === 823423)
    console.log(result);

    exercise = "Delete the comment with the ID of 823423";
    console.log("%c" + exercise + ":", "color: white; font-size: large");
    console.table(comments);
    comments.splice(result, 1)
    console.table(comments);

  </script>
</body>
</html>

5.3 Exercise: Elements By Tag Name (FDw2)

From: https://eloquentjavascript.net/14_dom.html#i_VSftnyRTsV

<h1>Heading with a <span>span</span> element.</h1>
<p>A paragraph with <span>one</span>, <span>two</span>
  spans.</p>

<script>
  function byTagName(node, tagName) {
    let nodeList = []

    function findTagName(node, tagName) {
      if (node.nodeName === tagName.toUpperCase()) {
        nodeList.push(node)
      }
      for (child of node.children) {
        findTagName(child, tagName)
      }
    }
    findTagName(node, tagName);

    return nodeList;
  }

  console.log(byTagName(document.body, "h1").length);
  // → 1
  console.log(byTagName(document.body, "span").length);
  // → 3
  let para = document.querySelector("p");
  console.log(byTagName(para, "span").length);
  // → 2
</script>

5.4 Exercise: Mouse Trail (FDw3)

From: https://eloquentjavascript.net/15_event.html#i_NOgRH0Y9st

let elementID = 0;

document.body.onmousemove = placeDiv;

// Create trail object
function trailObject(totalTime, id) {
  let time = totalTime;
  let hueStep = 360 / totalTime;
  let hue = 0;

  // Start interval
  let timer = setInterval(countdown, 100);
  function countdown() {
    // Remove element
    if (time <= 0) {
      document.getElementById(id).remove()
      clearInterval(timer)
    }
    // Count down & animate element
    else {
      time -= 1;
      document.getElementById(id).style.background = "hsl(" + hue + ",100%,50%)";
      hue += hueStep;
    }
  }
}

// Place element
function placeDiv(e) {
  let element = document.createElement('div');
  element.id = elementID;
  element.classList.add('trail');
  element.style.left = e.clientX + "px";
  element.style.top = e.clientY + "px";
  document.body.appendChild(element);

  trailObject(10, elementID);

  elementID += 1;
}