Skip to content

Artikels

romyjkk edited this page Dec 1, 2022 · 5 revisions

Vooral aan het begin van de tech-track, heb ik veel artikelen gelezen aangezien ik graag up-to-date wilde blijven en alles goed wilde snappen. Hier zijn al m'n aantekeningen voor artikels en freecodecamp opdrachten te vinden!

Week 1

Zelfstudie

splice() changes the original array it is called on. One of the core principles of functional programming is to not change things, changes lead to bugs.

Declare your dependencies explicitly. If a function depends on a variable/object being present, pass that variable/object directly into the function as an argument.

delete object.key; → delete een key.

If you want to check if an object has a specific property use hasOwnProperty() or in.

charAt() → returns a string consisting of the single UTF-16 code unit located at the specified offset into the string.

In the parameters you can add index . This is an integer between 0 and str.length -1. If the index you supply is out of range, JS will return an empty string.

Article - Data mutation in functional JavaScript

The purpose of normalization is to transform/reduce one data structure into another one, so it’s straight forward to use Array.prototype.reduce.

Article - What is functional programming? A beginner’s JavaScript guide

Programming paradigm → essentially a bunch of rules that you follow when writing code.

Functional programming is a sub-paradigm of the declarative programming paradigm.

If you code in a language that follows the declarative paradigm, you write code that specifies what you want to do, without saying how.

If you code in a language that follows the imperative/procedural paradigm, you write code that tells how to do something.

JavaScript can do both.

Functional programming is a sub-paradigm from the declarative paradigm and it affects the way you write functional code. It usually leads to less code.

Functional programming can be simply explained by following two laws in your code:

  • Architect your software out of pure, isolated functions
    • Pure functions: the same input always gives the same output and has no side effects. An idempotent function is one that, when you reapply the results to that function again, it doesn’t produce a different result.
    • Side effects are when your code interacts with external mutable state (anything outside the function).
    • Isolated functions: there’s no dependence on the state of the program, which includes global variables that are subject to change.
    • Functions that can be assigned to a variable, passed into another function or returned from another function are called first class functions. In JS, all functions are like this. They allow us to create higher order functions, which is a function that either takes a function as an argument, returns a function, or both.
    • The built in JS array functions .map, .reduce and .filter all accept a function.They iterate over an array and call the function they received for each item in the array.
  • Avoid mutability and side-effects
    • Don’t change things! Once you’ve made it, it’s immutable (unchanging). If something has to change, make a copy.
    • If we can’t change the state of global variables, you need to ensure:
      • We declare function arguments
      • We don’t alter a variable or object
    • Make your code referentially transparent → happens when you never change anything. Your function calls can be replaced with the values they represent without affecting the results.
    • Use map instead of for loops.

A base case → lets the function eventually stop calling into itself infinitely.

Recursion allows us to stop mutating state variables. There’s also certain data structures that are more efficient when solved with recursion.

Currying is also a tool used heavily in functional code. The arity of a function refers to how many arguments it receives. Currying a function turns a function that has an arity of more than one, to one. Currying is good when you re-use the same function multiple times and only have to change one or less parameters.

Partial application means that you apply a few arguments to a function at a time and return another function that is applied to more arguments.

Function composition allows us to take two or more functions and return them into one function that does exactly what those two do. Composition allows you to structure your code out of re-usable functions, to stop repeating yourself.

Article - JavaScript Arrays

An array is a global object that’s used to store data in JavaScript. They consist of an ordered selection or list containing zero or more data types. They use numbered indices starting at 0. They’re super usefull since they store multiple values in a single variable. Arrays can contain any data type.

Creating an array

Syntax: let Array = [];

This allows you to store multiple elements in a single variable instead of making a bunch of variables containing one element each.

Accessing items in an array

Accessing a specific item: Array[0].

You can also make an array like this: let name = new Array("data", "data"); (may have inconsistencies/unexpected results.

Arrays can contain other arrays.

If you want to find out the index number of a specific item in an array, you can use indexOf(). If there’s no index number to be found the console will return -1.

You can, for example, find the last item in an array by using the length property and applying that as the new index number: const lastIndex = array.length - 1; array[lastIndex];

In order to acces items in a nested array, you need to add another index number to access the inner array.

Adding an item to an array

You can assign a new item to the array: array[5] = "data";.

A better way to do this is by using the push() method. This adds an item to the end of the array: array.push(”data”);

array;

On the other hand, unshift() will add an item at the beginning of the array.

Removing items from an array

You can also remove items from arrays. You can use splice() for that. In the parameter you add two numbers, the first one is the index number that has to be removed and the second one is how many should be removed. splice() will change the original variable. If you don’t want this to happen, you can use slice() instead. You can assign the result to a new variable so the original one will remain unchanged.

You can use the concat() method to return a new array.

The pop() mehod will remove the last item in an array. This method is preffered when possible, since the other items in the array will keep their index numbers.

With shift() you can remove the first item of the array.

Modifying values in array

You can overwrite any value in an array by assigning a new value using the assignment operator: array[1] = "new value";

Another way to modify a value is using the splice() method with a new parameter: array.splice(3, 1, “new value”);

Looping through an array

You can loop through the entirety of an array with the for keyword, taking advantage of the length property:

for (let i = 0; i < array.length; i++) {

console.log(i, array[i]);

}

You can also use the for ... of loop:

for (let array of arrays) {

console.log(array);

}

This loop does not retrieve the index number of the elements in the array, but it’s generally a simpler, more concise way to loop thorugh an array.

Article - JavaScript Functions

Function → a block of code that performs an action or returns a value. They’re custom code defined by programmers that are reusable.

Defining a function

Functions are defined with the function keyword.

Calling a function: name();

Function parameters

Using parameters you can additional functionality that will make the code more flexible.

Parameters → input that gets passed into functions as names and behave as local variables.

Variables can be declared inside of functions, they’re known as local variables and only exist inside the function block.

Returning values

You can pass multiple values into a parameter.

Function expressions

You can create a function expression by assigning a function to a variable.

You can turn it into an anonymous function (unnamed function).

Arrow functions

A newer, more concise method of defining a function is an arrow function expression. They’re represented by =>. They’re always anonymous functins and a type of function expression.

In the case of only one parameter, the parantheses can be excluded.

Article - How to use the filter() array method in JavaScript

The filter() array method creates a new array with elements that fall under a given criteria from an existing array.

Syntax: var newArray = array.filter(function(item) {

return condition;

});

The item argument is the element in the array as filter() checks it against the condition.

Using filter() on an array of objects

You can filter an array of different objects, syntax:

var newArray = arrays.filter(function(array) {

return array.key == "Data";

});

console.log(newArray);

This will only show the specified key.

Week 2

D3

D3 is flexible, you can do whatever you want - creative freedom. There’s many different possibilities, like animation.

Observable → the ideal environment for learning D3: it simplifies code with dataflow. You can add interaction or animation with almost no code.

Data Visualization with D3

The select() method selects one element from the document. The append() method takes an argument for the element you want to add to the document. The text() method either sets the text of the selected node, or gets the current text.

D3 also has the selectAll() method to select a group of elements.

The data() method is used on a selection of DOM elements to attach the data to those elements. The enter() method is used to create a new element in the document for every piece of data in the set. When enter() is combined with the data() method, it looks at the selected elements from the page and compares them to the number of data items in the set.

The D3 text() method can take a string or a callback function as an argument.

D3 lets you add inline CSS using the style() method.

You can use a callback function in the style() method to change the styling for different elements.

d is used to represent the data point.

It’s easier to add a class to elements and style that class one time. You can use attr() to add any HTML attribute to an element, including a class name. It works the same as style(): it takes comma seperated values and can use a callback function. Syntax on how to add a class to a selection:

selection.attr("class", "container");

SVG stands for Scalable Vector Graphics SVG shapes for a web page must go in the svg tag in HTML.

Creating and appending a div for each item in the dataset:

d3.select("body").selectAll("div")
  .data(dataset)
  .enter()
  .append("div")

The placement of an svg rectangle is handled by the x and y attributes. For a bar chart for example, the bars should sit on the same vertical level, which means the y value stays the same. Any method that’s chained after data() is run once for each item in the data set. Syntax for making each bar in a a bar chart have a different position:

.attr("x", (d, i) => { (d → data point value, i → the index of the data point)

return i * 30

})

You can also dynamically change the height of each bar.

Invert SVG elementsy = heightOfSVG - heightOfBary = h - i * d

D3 lets you label a graph element, like a bar, using the SVG text element. Just like rect, it needs to have x and y attributes to place it on the SVG canvas. It also needs to access the data to display the values.

You can use attr() and then the :hover pseudo-class to add hover effects.

A tooltip shows more information about an item on a page when the user hovers over the item. You can do that, for example, by using the SVG title element.

Syntax for something: .text((d, i) => d)

SVG has a circle tag to create a circle shape. It works a lot like rect.

A circle has three main attributes. The cx and cy attributes are coordinates. This is where the center of the shape will be on the SVG canvas. The radius attribute gives the size of the circle. All three can use a callback function to set their values dynamically.

scales are functions that tell the program how to map a set of raw data points onto the pixels of the SVG canvas. For linear scale (quantitative data) you can use scaleLinear(). const scale = d3.scaleLinear()

The value ranges from 50 to 480 → this is the input information for a scale, also known as the domain. You want to map them between 10 and 500 units. This is the range. The domain() and range() methods set these values for the scale. They both take an array of at least two elements as an argument.

D3 has two methods - min() and max() to return the minimum and maximum values in a dataset.

The min() and max() methods are useful to help set the scale.

const dataset = [
  [ 34,    78 ],
  [ 109,   280 ],
  [ 310,   120 ],
  [ 79,    411 ],
  [ 420,   220 ],
  [ 233,   145 ],
  [ 333,   96 ],
  [ 222,   333 ],
  [ 78,    320 ],
  [ 21,    123 ]
];
const w = 500;
const h = 500;

const padding = 30;
const xScale = d3.scaleLinear()
  .domain([0, d3.max(dataset, (d) => d[0])])
  .range([padding, w - padding]);

In this example the domain goes from 0 to the maximum in the set. The range uses the SVG canvas’ width w, but also includes some padding.

Scale functions keep the data within the screen’s plotting area. You don’t need to apply scales when you display the actual data value, for example, in the text() method for a tooltip or label.

Another way to improve a scatter plot → add an x-axis and y-axis. D3 has two methods - axisLeft() and axisBottom() to render both. An example to create an x-axis based on the xScale : const xAxis = d3.axisBottom(xScale); The next step is to render the axis on the SVG canvas. You can use a general SVG component, the g element, to do that. It stands for group. The last step is applying a transform attribute to position the axis on the SVG canvas in the right place. Positioning axis needs translate. Making an x + y-axis:

const xAxis = d3.axisBottom(xScale);
const yAxis = d3.axisLeft(yScale);

    svg.append("g")
       .attr("transform", "translate(0," + (h - padding) + ")")
       .call(xAxis);

   svg.append("g")
      .attr("transform", "translate(" + padding + ",0)")
      .call(yAxis);

JSON APIs and AJAX

If you want your code to execute only once your page finished loading → use DOMContentLoaded:

document.addEventListener('DOMContentLoaded', function() {

});

You can implement an onclick event handler which triggers when the user clicks on the element.

When the click event happens you can use JS to update an HTML element: document.getElementsByClassName('message')[0].textContent="Here is the message";

JSON syntax looks similar to JavaScript objects. It has object properties and their current values sandwhiched between a { and }. They’re often reffered to as key-value pairs. JSON transmitted by API are sent as bytes and your application receives it as a string. They can be converted to JSobjects, but are not JSobjects by default. The JSON.parse method parses the string and constructs the JS object described by it. When requesting data from an API → GET request.

Another way to request external data → using the JS fetch() method. Code for making a GET request to /json/cats.json:

fetch('/json/cats.json') **->** **makes a GET request to the URL specified.**
  .then(response => response.json()) **->** ******************************************************************************************************************promise returned, takes the response and converts it to JSON******************************************************************************************************************
  .then(data => { -> ******************************************************************-> also returns promise, the JSON object you're looking for******************************************************************
    document.getElementById('message').innerHTML = JSON.stringify(data);
  })

[] → array {} → object ” “ → string

"id":0id is a key, 0 is the corresponding value.

You can use a forEach method to loop through data in an array.

Week 4

Oh Snap! - Adam Argyle

Handig voor storytelling

Change the direction of scrollers. overflow-block is scrolling vertically.

Root scroller → top scroller. Implicit scroller → a nested scroller, anything that’s not a root scroller.

Scroll behavior → control if browser scroll should be instant or animated using CSS or JS. Overscroll behavior → should a nested scroller trap it’s inertia or not. Overscroll effect → UI feedback informing users they’re at the beginning/end of a scroller. Scroll hint → UI to help users see there’s room to scroll.

Scroll snap → a way to scroll? Any child can be a snap destination.

Altijd overscroll-behavior: contain; gebruiken. Anders scroll je door.