Jeremy Troy Suchanski                                   

Web Frontend Development II

Gary James                                                                  

May 10, 2022

L07 Readings Notes

Ch11: Further Functions (Notes)

The Properties and Methods of All JavaScript Functions

const clark = { name: 'Clark' };

const bruce = { name: 'Bruce' };

sayHello.call(clark);

<< 'Hello, my name is Clark'

sayHello.call(bruce);

<< 'Hello, my name is Bruce'

If the function that’s called requires any parameters, these need to be provided as arguments after the first argument, which is always the value of this. Code Example

function sayHello(greeting='Hello'){

  return `${ greeting }, my name is ${ this.name }`; }

sayHello.call(clark'How do you do');

<< 'How do you do, my name is Clark'

sayHello.call(bruce);

<< 'Hello, my name is Bruce'

If a function doesn’t refer to an object as this in its body, it can still be called using the call() method, but you need provide null as its first argument. (i.e. square.call(null, 4))

square.description = 'Squares a number that is provided as an argument'

function square(x){

  square.cache = square.cache || {};

  if (!square.cache[x]) {

      square.cache[x= x*x; }

  return square.cache[x] }

(function(){

  const temp = 'World';

  console.log(`Hello ${temp}`);

  })();

  << 'Hello World'

IIFE Temporary Variables: There is no way to remove a variable from a scope once it’s been declared. IIFEs are a useful way of performing a task while keeping any variables wrapped up within the scope of the function. Can be used to swap values within a scope.

let [a,b= [1,2];

[a,b= [b,a];

IIFE Initialization Code: code that there’ll be no need for again. Can set up any variables, objects and event handlers for one use out of scope.

{

  const name = 'Peter Parker'// This might be obtained from a cookie in reality

  const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday',                                                                'Friday','Saturday'];

  const date = new Date(),today = days[date.getDay()];

  console.log(`Welcome back ${name}. Today is ${today}`); 

}

<< 'Welcome back Peter Parker. Today is Tuesday'

IFFE Strict Mode: the recommended way to use strict mode is to place all your code inside an IIFE with “use strict” right under (function() {

IFFE Self-contained Code Blocks: encloses a block of code inside its own private scope so it doesn’t interfere with any other part of the program. This can be achieved in ES6 by simply placing the different parts of code into blocks.

Functions that Define and Rewrite Themselves

Code Example

function party(){

  console.log('Wow this is amazing!');

  party = function(){

      console.log('Been there, got the T-Shirt'); } }

function ride(){

    if (window.unicorn) { 

        ride = function(){

        // some code that uses the brand new and sparkly unicorn methods

        return 'Riding on a unicorn is the best!'; }

    } else {

        ride = function(){

        // some code that uses the older pony methods

        return 'Riding on a pony is still pretty good'; } }

    return ride(); }

function factorial(n) {

    if (n === 0) {

        return 1;

    } else {

        return n * factorial(n - 1); } }

function wait(messagecallbackseconds){

    setTimeout(callback,seconds * 1000);

    console.log(message); }

function selfDestruct(){

    console.log('BOOOOM!'); }

wait('This tape will self-destruct in five seconds ... 'selfDestruct5);

console.log('Hmmm, should I accept this mission or not ... ?');

<< 'This tape will self-destruct in five seconds ... '

<< 'Hmmm, should I accept this mission or not ... ? '

<< 'BOOOOM!'

const promise = new Promise( (resolvereject=> {

    // initialization code goes here

    if (success) {

        resolve(value);

    } else {

        reject(error); } });

if-else block: used below to specify the conditions for success (rolling any number higher than 1) and failure (rolling a 1) Code Example:

const promise = new Promise( (resolve,reject=> {

    const n = dice.roll();

    setTimeout(() => {

        (n > 1? resolve(n: reject(n);

    }, n*1000); });

promise.thenresult => console.log(`Yes! I rolled a ${result}`), result => console.log(`Drat! ... I rolled a ${result}`) );

promise.catchresult => console.log(`Drat! ... I rolled a ${result}`));

promise.thenresult => console.log(`I rolled a ${result}`) )

            .catchresult => console.log(`Drat! ... I rolled a ${result}`) );

 login(userName)

.then(user => getPlayerInfo(user.id))

.then(info => loadGame(info))

.catchthrow error)

async function loadGame(userName) {

    try {const user = await login(userName);

         const info = await getPlayerInfo (user.id);

        // load the game using the returned info }

    catch (error){throw error;} }

function random(a,b,callback) {

    if (b === undefinedb = aa = 1// if only one argument is supplied, assume the lower limit is 1

        const result = Math.floor((b-a+1* Math.random()) + a

    if(callback) {

        result = callback(result); }

    return result; }

function greeter(greeting = 'Hello') {

    return function() {

        console.log(greeting); } }

const englishGreeter = greeter(); // greeter() called

englishGreeter();

<< Hello

const frenchGreeter = greeter('Bonjour'); // greeter called

frenchGreeter();

<< Bonjour

const germanGreeter = greeter('Guten Tag'); // greeter called

germanGreeter();

<< Guten Tag

function outer() {

    const outside = 'Outside!';

    function inner() {

        const inside = 'Inside!';

        console.log(outside);

        console.log(inside); }

    console.log(outside);

    inner(); }

outer()

<< Outside!

Inside!

Outside!

function outer() {

    const outside = 'Outside!';

    function inner() {

        const inside = 'Inside!';

        console.log(outside);

        console.log(inside); }

    return inner; }

const closure = outer();

closure();

<< Outside!

Inside!

function counter(start){

    let i = start;

    return function() {

        return i++; } }

const count = counter(1);

count();

<< 1

count();

<< 2

yield: Generator functions employ this special keyword that is used to return a value. The difference between the yield and the return keywords is that by using yield, the state of the value returned is remembered the next time yield is called. Code Example:

function* fibonacci(a,b) {

    let [ prev,current ] = [ a,b ];

    while(true) {

        [prevcurrent= [currentprev + current];

        yield current; } }

const sequence = fibonacci(1,1);

sequence.next();

<< 2

sequence.next();

<< 3

sequence.next();

<< 5

iterating over the generator: this will invoke the generator multiple times. In the example the sequence will continue from the last value produced using the next() method, because a generator will maintain its state throughout the life of a program. Code i.e.:

for (n of sequence) {

    // stop the sequence after it reaches 100

    if (n > 100break;

    console.log(n); }

<< 8 << 13 << 21 << 34 << 55 << 89

Pure Functions: A key aspect of functional programming is its use of pure functions. (A pure function is a function that adheres to the following rules: #1 The return value of a pure function should only depend on the values provided as arguments. It doesn't rely on values from somewhere else in the program. #2 There are no side-effects. A pure function doesn't change any values or data elsewhere in the program. It only makes non-destructive data transformations and returns new values, rather than altering any of the underlying data. #3 Referential transparency. Given the same arguments, a pure function will always return the same result.) A pure function must have #1 at least one argument #2 a return value. By only performing a single task, pure functions are more flexible, as they can be used as the building blocks for many different situations

const: using const to declare variables will help to avoid destructive data transformations. (although variables that are assigned to non-primitive objects using const can still be mutated, so it's not a complete solution).

     Code Example:

const number = 42;

function pureAdd(x,y) {

    return x + y; }

result = pureAdd(number,10);

<< 52

            function composition: using functions as the building blocks of functions. Code i.e.:

function variance(array) {

    return sum(array,square)/array.length - square(mean(array)) }

    variance([1,2,3])

    << 0.666666666666667

function multiplier(x){

    return function(y){

        return x*y; } }

doubler = multiplier(2);

doubler(10);

<< 20

tripler = multiplier(3);

tripler(10);

<< 30

using double parentheses: create an anonymous return function and immediately invoke it. This example works because power(3) returns a function, to which we immediately pass an argument of 5 by adding it in parentheses at the end. Code Example:

function power(x) {

    return function(power) {

        return Math.pow(x,power); } }

twoExp = power(2);

<< function (power) {

    return Math.pow(x,power); }

twoExp(5);

<< 32

power(3)(5);

<< 243

function multiplier(x,y) {

    if (y === undefined) {

        return function(z) {

        return x * z; }

    } else {

        return x * y; } }

calcTax = multiplier(0.22);

<< function (z){

    return x * z; }

calcTax(400);

<< 88   

 

Ch8: Transforms and Transitions (Notes)

transformtranslate(45px-45px);

transformtranslateX(45px);

transformtranslateY(-30px);

transformscale(1.50.25);

transformscale(1)/* Maintains the same size with size*1 */

transformscale(2)/* Doubles the size with size*2 */

transformscaleX(1.5);

transformscaleY(1.5);

transformtranslateX(40pxscale(1.5);

transformrotate(10deg)

transformskew(15deg4deg);

transformskewX(15deg);

transformskewY(15deg);

transform-origin10% 10%;

transformrotate(180deg);

transition-propertytransform;

more than 1 property

transition-propertytransform, color;

older browsers

-webkit-transition-property-webkit-transform;

transition-propertytransform;

transition-duration0.2s;

ease: default key term for transition-timing-function that has a slow start, then it speeds up, and ends slowly.

ease-in-out: key term for transition-timing-function that is similar to ease, but accelerates more sharply at the beginning.

linear: key term for transition-timing-function that creates a transition that animates at a constant speed.

ease-in: key term for transition-timing-function that creates a transition that is slow to start but gains speed, then stops abruptly.

ease-out: key term for transition-timing-function that starts at full speed, then slows progressively as it reaches the conclusion of the transition.

Code Example

transition-timing-functionease-out;

-webkit-transition-delay50ms;

transition-delay50ms;

transition-propertytransform

transition-duration0.2s;  

transition-timing-functionease-out;

transition-delay50ms;

shorthand =

transitiontransform 0.2s ease-out 50ms;

transition-propertytransform, color

transition-duration0.2s0.1s;  

transition-timing-functionease-out, linear;

transition-delay50ms;

 transitiontransform 0.2s ease-out 50ms, color 0.1s linear 50ms;

transitionall 0.2s ease-out 50ms;

keyframe: a snapshot that defines a starting or end point of any smooth transition. With CSS transitions, you’re essentially limited to defining a first and a last keyframe. CSS animations allow you to add any number of keyframes in between, to guide our animation in more complex ways. (the -webkit- prefix in iOS8, Android 4.4.3, and BlackBerry 10 is required) Generally, it is best to use CSS for simple-state changes in a mobile environment.

Code Examples

@keyframes moveRight { 

  from {

  transformtranslateX(-50%);

  }

  to {

  transformtranslateX(50%);

  }

}

@keyframes appearDisappear { 

  0%, 100% {

  opacity0;

  }

  20%, 80% {

  opacity1;

  }

}

@keyframes bgMove {

  100% {

  background-position120% 0;

  }

}

animation name property: names the animation.

animation-duration property: defines the length of time (in seconds or milliseconds) an animation takes to complete one iteration (all the way through, from 0% to 100%). 

animation-timing-function: determines how the animation will progress over its duration. The options are the same as for transition-timing-function: ease, linear, ease-in, ease-out, ease-in-out, a developer-defined cubic-bezier() function, step-start, step-end, or a developer-defined number of steps with the steps(number, direction) function.

animation-iteration-count property: lets you define how many times the animation will play through. The value is generally an integer, but you can also use numbers with decimal points (in which case, the animation will end partway through an iteration), or the value infinite for endlessly repeating animations. If omitted, it will default to 1.

animation-direction property: The value of reverse will cause the animation to start at the 100% keyframe and work its way to the 0% keyframe for every iteration. With the alternate value, the initial iteration and odd-numbered iterations after that will go in the normal 0% to 100% direction, but the second iteration and every even iteration after that will go in the reverse direction of 100% to 0%. Similarly, the alternate-reverseanimation-direction value causes the animation to alternate direction at every iteration, but it starts in reverse. When animations are played in reverse, timing functions are also reversed; for example, ease-in becomes ease-out.

animation-delay property: used to define how many milliseconds or seconds to wait before the browser begins the animation

animation-fill-mode property: defines what happens before the first animation iteration begins and after the last animation iteration concludes. (default behavior animation-fill-mode: none) The available values are none, forwards, backwards, or both.

  1. backwards: keyword that tells the animation to sit and wait on the first keyframe from the moment the animation is applied to the element, through the duration of the animation delay, until the animation starts iterating.
  2. forwards: keyword that holds the element at the last keyframe, with last keyframe property values overriding the element's original property values, without reverting to the original values at the conclusion of the last animation iteration.
  3. both: keyword that does both the backwards and forwards key words actions.

animation-play-state property: defines whether the animation is running or paused.

Code Examples:

animation-nameappearDisappear;

animation-duration300ms;

animation-timing-functionlinear;

animation-iteration-countinfinite;

animation-directionalternate;

animation-delay50ms;

animation-fill-modeboth;

animation-play-staterunning;

Shorthand animation Property: The animation property takes as its value a space-separated list of values for the longhand animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state properties. (Note that in the shorthand version, the animation-iteration-count and animation-play-state were left out since both were set to default.) Code Example

.verbose {

  animation-nameappearDisappear

  animation-duration300ms

  animation-timing-functionease-in;

  animation-iteration-count1;

  animation-directionalternate;

  animation-delay5s;

  animation-fill-modebackwards;

  animation-play-staterunning;

}

 

/* shorthand */

.concise {

  animation300ms ease-in alternate 5s backwards appearDisappear;

}