live-coding practice Flashcards

1
Q

*How do you declare an object

A

(literal) const blah = {}, (constructor) new Object(), Object.create()
—————————————————————
Actually there’s 6 ways:

Object Literal
Object Constructor
Constructor Function
Object.create() Method
Object.assign() Method
ES6 Classes

https://attacomsian.com/blog/javascript-create-object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

*How do you declare an array

A
(literal) const blah = [], (constructor) new Array(), Array.from()
—————————————————————
// using the new keywrod
const array1 = new Array("1", "2")
console.log(array1)
// array literal
const array2 = [true, false]
console.log(array2)
// using the from method, createds a shallow copy array
// doesn't work in IE
const array3 = Array.from(array2)
console.log(array3)
// you can spread one array into another one
const sup = ['1', '2']
const sup2 = [...sup]
console.log(sup2)

—————————————————————

Not sure if this counts as declaring an array but … you can create an array from objects like this

// You can create an array from an objects values using Object.values
const obj1 = {
    name: "brad",
    age: "12",
}
console.log(Object.values(obj1))
>> [ 'brad', '12' ]

// Or you could do it from an object’s keys using Object.keys
console.log(Object.keys(obj1))
» [‘name’, ‘age’]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

*IMplement the revealing module pattern

A

There’s also something called the ‘revealing module pattern’ where you return stuff out of your IIFE for use elsewhere. For example in the code below I return an object for use:

    const myName = (function() {
        function logFn(){
            console.log("hello");
        }
        return {logStuff: logFn}
    })()
Now I can use stuff like myName.name in other places
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you implement inheritance

A
ES6 way with classes:
        class Player {
          constructor(name, type) {
            console.log(this, "From player")
            //console.log(name, `This is the name inside the Player class`)
            this.name = name;
            this.type = type;
          }
      introduce() {
        console.log(`Hi my name is ${this.name}, I'm a ${this.type}`)
      }
    }
        class Wizard extends Player {
          constructor (name, type) {
            //console.log(name, `This is the name inside of the wizard class`)
            let othertype = "billy";
            let othername = "mark"
            super(othername, othertype)
            console.log(this, "From Wizard")
          }
          play() {
            console.log(`Weeee I'm a ${this.name}, of type ${this.type}`)
          }
        }
        const wizard1 = new Wizard('Shelly', 'Healer')
        const wizard2 = new Wizard('Shawn', 'tank')
    wizard2. introduce()
    wizard2. play()

    wizard1. introduce()
    wizard1. play()

Pre-es6 way with prototypes:
        var Player = function(name, type) {
          this.name = name;
          this.type = type;
        }
    Player.prototype.introduce = function() {
      console.log(`Hi I'm ${this.name} of type ${this.type}`)
    }
        var wizard1 = new Player("Shelly", "healer");
        var wizard2 = new Player("Billy", "tank");
    wizard1.play = function() {
      console.log(`Weeee, I'm a ${this.type}`)
    }

    wizard2.play = function() {
      console.log(`Woop, I'm also a ${this.type}`)
    }

    wizard1. introduce()
    wizard1. play()

Learn classes and extends from 20:53 https://www.udemy.com/course/advanced-javascript-concepts/learn/lecture/13511600#search
Can relearn classes and prototypes with this udemy section: https://www.udemy.com/course/javascript-beginners-complete-tutorial/learn/lecture/17190250#search

^that’s a setup, with a missing constructor in the child objects, that you would use if you don’t need to add any particular opening variables to the child and just want to use the parents constructor

Video tutorial on this one: https://www.udemy.com/course/javascript-beginners-complete-tutorial/learn/lecture/17190274#announcements

Also figured out how to do it like this:

>>const Player = function(name, age) {
      this.name = name;
      this.age = age;
  }
  //Player.prototype = new Player("billy", 12)
  Player.prototype.sayname = function() {
      console.log(`My name is ${this.name} and I am ${this.age} old`)
  }
>>const Athlete = function(sport, name, age) {
      Player.call(name, age)
      this.sport = sport;
  }

Athlete.prototype.saysport = function() {
console.log(I play ${this.sport})
}

const bobby = new Athlete(“soccer”, “billy”, 12)
bobby.saysport()
bobby.__proto__ = new Player(“billy”, 12)
//console.log(bobby.__proto__)
bobby.sayname()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Create a constructor function that hides a variable and then create new instances of it which can manipulate their version of that variabl without having direct access.

A
function Ninja() {
      let feints = 0;
      this.getFeints = function() {
        return feints;
      }
      this.feint = function() {
        feints++;
      }
    }
    let ninja1 = new Ninja();
    ninja1.feint(); // increae value of feints
console. log(ninja1.feints, "can't access feints directly for ninja1");
console. log(ninja1.getFeints()); // return value of feints, for ninja1
    let ninja2 = new Ninja();
    console.log(ninja2.getFeints()); // return feints for ninja2
  1 const Stuff = function() {
  2     let name = "TEMPORARY";
  3
  4     return {
  5         sayname: function() {
  6             console.log(name)
  7         },
  8         setname: function(input) {
  9             name = input
10         }
11     }
12
13     //this.sayname = function() {
14     //    console.log(name);
15     //}
16
17     //this.setname = function(newname) {
18     //    name = newname;
19     //}
20
21 }
22
23 const bobby = Stuff()
24
25 bobby.sayname()
26 bobby.setname("brad")
27 bobby.sayname()
28 const sarah = new Stuff()
29 sarah.sayname()
30 sarah.setname("sarah")
31 sarah.sayname()
32 bobby.sayname()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Create your own promise object for use

A
let PENDING = 0;
    let FULFILLED = 1;
    let REJECTED = 2;
    function CustomPromise(executor){
      let state = PENDING;
      let value = null; //the this.then method will use this
      let handlers = []; // the this.then method will use this to throw additional callack functions into
      let catchers = []; // the this.thn will also dump callback functions in here but ... yah
      function resolve(result) {
        if (state !== PENDING) return;
        state = FULFILLED;
        value = result;
        handlers.forEach(func => {
          func(value)
        })
      }
      function reject(error) {
        if (state !== PENDING) return;
        state = REJECTED;
        value = error;
        catchers.forEach(ruin => ruin(value))
      }
  this.then = function(additionalFunction) {
    if (state === FULFILLED) {
      additionalFunction(value);
    } else {
      handlers.push(additionalFunction)
    }
  }

  executor(resolve, reject);
}
    const doWork = (res, rej) => {
      setTimeout(() => {
        res("HelloWorld");
      }, 1000);
    }
let someText = new CustomPromise(doWork)

someText.then((res) => console.log(res));
someText.then(sup => console.log(sup));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Demonstrate the difference of this between a normal function and an arrow function

(refer to anki deck for images which are … excellent ones. I need to convert those to text actually)

A

This is the object that the function is a property of

Benefits include

  1. It gives methods access to their object
  2. You can execute the same code for multiple objects

https: //www.udemy.com/course/advanced-javascript-concepts/learn/lecture/13772916#search
https: //www.udemy.com/course/advanced-javascript-concepts/learn/lecture/13772930#search <– the examples below are from this video

… might want to spend time updating this answer with better, more explainy, code examples

Longer definition: This refers to the object that calls the function since it has runtime binding (dynamically scoped - not lexically scoped)most of th time. Behavior differs when explicitly setting its value with bind, apply, and call, and also arrow functions do not provide their own this binding, it retains the value from its enclosing lexical environment instead.

demonstrate this and explain:
        const a = function() {
          console.log('a', this) // window => window.a()
          const b = functio\\\\\n() {
            console.log('b', this) // window => window.a( /* b() */ )
            const c = {
              hi: function() {
                console.log('c', this) // c => window.a ( /* b( /* c.hi() */ ) */)
              }
            }
            c.hi()
          }
          b()
        }
    a()
        // a function // output 'a' window // var b
        // b function // output 'b' window // var c b
        // c.hi function // output 'c' c // var c
another example:
        var b = {
          name: 'b',
          say() { console.log(this)}
        }
        var c = {
          name: 'c',
          say() { return function() { console.log(this)}}
        }
        var d = {
          name: 'd',
          say() { return () => console.log(this)}
        }
    d. say()() //d
    c. say()() //window
    b. say() //b

«&laquo_space;some more&raquo_space;>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Demonstrate different ways to make this fourth this variable not refer to the global object

    const first = function() {
      console.log('first this is: ' + this);
      const second = function() {
        console.log('second this is: ' + this)
        const third = {
          printThird: function() {
            console.log('third this is: ' + this)
            const fourth = function() {
              console.log('fourth this is: ' + this)
            }
            fourth()
          }
        }
        third.printThird()
      }
      second();
    }      
    first()
A
const first = function() {
      console.log('first this is: ' + this);
      const second = function() {
        console.log('second this is: ' + this)
        const third = {
          printThird: function() {
            console.log('third this is: ' + this)
            const fourth = function() {
              console.log('fourth this is: ' + this)
            }
            fourth()
          }
        }
        third.printThird()
      }
      second();
    }      
    first()
// fixed version below with arrow function
        const fourth = () => {
          console.log('fourth this is: ' + this)
// fixed version below binding this to a variable
        const third = {
          printThird: function() {
            console.log('third this is: ' + this)
            that = this;
            const fourth = function() {
              console.log('fourth this is: ' + that)
            }
            fourth()
          }
        }
    // call version below
    // apply, bind not shown
    const first = function() {
     console.log('first this is: ' + this);
     const second = function() {
       console.log('second this is: ' + this)
       const third = {
       printThird: function() {
          console.log('third this is: ' + this)
          const fourth = function() {
           console.log('fourth this is: ' + this)
          }  
          fourth.call(third)
        }
       }  
       third.printThird()
     }
     second();
    }   
    first()

// here is another version of this getting broken but includes commented out fixes
        const obj = {
          name: 'Billy',
          sing() {
            console.log('a', this);
            var anotherFunc = function() {
              console.log('b', this)
            }
            // anotherFunc.bind(obj)() //fix with bind
            // return anotherFunc.bind(this) // fix with bind to lcoal this
            return anotherFunc; // global this
          }
        }
    obj.sing()()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Demonstrate variable leakage and how to fix it

A
Leaks:
function stuff() {
  hello = function() {
    console.log("can you see me")
  }

}

stuff()
hello()

—————————————————————
fixed by using the let keyword, or const

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Demonstrate variable leakage and how to fix it

A
Leaks:
function stuff() {
  hello = function() {
    console.log("can you see me")
  }

}

stuff()
hello()

—————————————————————
fixed by using the let keyword, or const

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Demonstrate the use of call and apply and say what they do

A
const wizard = {
      name: "wizard",
      health: 20,
      heal() {
        this.health = 100;
        return `Just healed ${this} to 100 `;
      },
      gloat(num, realname) {
        console.log(`Heh, ${this.name} health is now over ${num} maybe, an my real name is ${realname}`)
      }
    }
    const shooter = {
      name: "shooter",
      health: 30,
    }
console.log(`The wizards health is ${wizard.health} and the shooters health is ${shooter.health}`)
wizard.heal.apply(shooter)
wizard.gloat.call(shooter, 5000, "bobby") //call differs from apply by taking comma separated parameters
wizard.gloat.apply(shooter, [20, "???"]) // apply differs by taking an array of parameters
// const sup = wizard.gloat.bind(shooter, 999999, "lol")
// sup()
wizard.gloat.bind(shooter, 1, 77777, "lol")() // bind, unlike call and apply, doesn't run immediately, instead it returns a function to be run in the future
console.log(`The wizards health is ${wizard.health} and the shooters health is ${shooter.health}`)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

give an example of function composition

A

“Function Composition” is applying one function to the results of another. · (g º f)(x) = g(f(x))

note: Function composition is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result.

Composing functions is where you take a set of pure functions and compose a new function that is a composition of all the functions
When we compose functions together, the main goal is to take a function and combine it with another function–so that when both of them are together gives us a more enhanced function that helps to produce a value that we want.

    const compose = (a, b) => (num) => a(b(num));
        const subtract = (num) => num - 1;
        const multiply = (num) => num * 5;
    const multiplyAndSubtract = (multiplyNum, subtractNum) => compose(multiplyNum, subtractNum);

    const doit = multiplyAndSubtract(subtract, multiply)

    doit(5)

another example:
    fn1(fn2(fn3(50)));
    compose(fn1, fn2, fn3)(50); // do 3, then 2, then 1 on the input of 50
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

give an example of partial application, and or properly describe it

A

Partial application is a process of reducing a function’s arity (the number of its parameters) by creating a new function with some of the arguments passed in.
Partial application allows us to fix a function’s arguments. This lets us derive new functions, with specific behavior, from other, more general functions.
Partial application starts with a function. We take this function and create a new one with one or more of its arguments already “set”
Partial application is the act of taking a function which takes multiple arguments, and “locking in” some of those arguments, producing a function which takes fewer arguments.
Partial application says on the second call of the function, I expect all the arguments while currying says I expect the arguments one at a time

    const multiply = (a,b,c) => a*b*c;
    const partialmultiply = multiply.bind(null, 5)
    console.log(partialmultiply(1,3))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

compare pipe to compose

A
It's just like compose except it swaps the order of the composition. in this case, we reverse the order in which functions are operated on data
        const compose = (a, b) => (num) => a(b(num));
        const pipe = (a, b) => (num) => b(a(num));
        const subtract = (num) => num - 1;
        const multiply = (num) => num * 5;
    const multiplyAndSubtract = (multiplyNum, subtractNum) => compose(multiplyNum, subtractNum);

    const doit = multiplyAndSubtract(subtract, multiply)

    doit(5)

another example:
    fn1(fn2(fn3(50)));
    pipe(fn3, fn2, fn1)(50); // do 3, then 2, then 1 on the input of 50
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

*How many types are there in javascript and what are they

A

There are 7:

        booleans
        strings
        numbers
        symbol
        undefined
        null
    object - this is a non primitive type as it doesn't have the value directly like the others. arrays, and function are objects too
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

*Quickly convert a variable to a number

A

you could use unary plus
console.log(+”10”)

console.log(Number(“10”)) is also correct

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

implement promise.all [with fetch?]

A

const urls = [
‘https://jsonplaceholder.typeicode.com/users’,
‘https://jsonplaceholder.typicode.com/posts’,
‘https://jsonplaceholder.typicode.com/albums’
]

Promise.all(urls.map(url => {
    return fetch(url).then(resp => resp.json())
    })).then(results => {
        console.log(results[0])
        console.log(results[1])
        console.log(results[2])
    }).catch(() => console.log('woops'))

// I should probably annotate this code above for reference
        const sup1 = Promise.resolve("done")
        const sup2 = Promise.resolve("done 2")
        const sup3 = Promise.resolve("done 3")
        const things = Promise.all([sup1, sup2, sup3])
        things.then(result => console.log(result[0]))
    console. log(things) https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

*loop through the properties of an object

A
const obj = {
      name: "billy",
      age: 12,
      value: false,
    }
    const obj2 = {
      color: "blue"
    }
    obj2.\_\_proto\_\_ = obj
console.log(obj2.color)
    for (const prop in obj2) {
      if (obj2.hasOwnProperty(prop)){
        // use hasOwnProperty so you don't get the prototypes properties as
        console.log(prop, obj[prop])
      }
    }
for (const [key, value] of Object.entries(obj2)){
  console.log(key, value)
}

for (const key of Object.keys(obj2)){
  console.log(key)
}

for (const value of Object.values(obj2)){
  console.log(value)
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is a factory function? Make one

A

A factory function is a function that creates objects

Here's one way
        function createHouse(height, width, color) {
          return {
            height,
            width: width,
            somecolor: color,
          }
        }
    const tallHouse = createHouse("huge", "5 feet wide", "blue")

    console. log(tallHouse.height)
    console. log(tallHouse.width)
    console. log(tallHouse.somecolor

Here's a better version:
        const shareSize = {
          size2: function() {
            console.log(this.height, this.width, this.size)
          }
        }
        const createHouse = function(height, width, size){
          const newHouse = Object.create(shareSize);
      newHouse.height = height;
      newHouse.width = width;
      newHouse.size = size;

      return newHouse;
    }

    const bobsHouse = createHouse('5 feet tall', '20 feet wide', "HUUUGE")
        console.log(bobsHouse)
        //console.log(shareSize.isPrototypeOf(bobsHouse))
    bobsHouse.size2()
const attack = function() {
    console.log('dont attack ' + this.name)
}
const objattack = {
    getem() {
        console.log("dont attack " + this.name)
    }
}

const Person = function(name, age) {

    const abilities = Object.create(objattack)
    //abilities.name = name;
    //abilities.age = age;
    //return abilities
    // return Object.assign(abilities, {name: name, age: age})
    return Object.assign(abilities, {name, age})
    // return {
    //     name: name,
    //     age: age
    // }
}
const bob = Person("bobby", 12)
bob.attack = attack
bob.attack()
const jerry = new Person("jerarmy", 12)
jerry.attack = attack
jerry.attack()
20
Q

make an example of how closures can make your program or function more memory efficient

A

For this,I can use the example from udemy course #78
Here are two different examples of how to do it. In these we call “the original” only once instead of a bunch of times like what would happen normally if repeatedly called a function

    let view;
    const dostuff = () => {
      let count = 0
      view = "nice";
      console.log(view, "the original")
      count++
      return () => {
        console.log(view, count)
      }
    }
const things = dostuff()
things()
things()
things()
let view2 = (function(){
    let count = 0;
    console.log('count is ' + count)
    count++;
    return console.log('the count was set') || 'something';
})()

====== below was originally there, but I don’t think it’s right ====

    let view2;
    const dothings = (() => {
      view2 = "good";
      console.log(view2, "original")
      return () => {
        console.log(view2)
      }
    })()
dothings()
dothings()
dothings()
21
Q

make an object using the function constructor

A

Here’s one example

        const Dude = new Function('name', 'height', `
          this.name = name;
          this.height = height;
          `)
        const gdude = new Dude('billy', 'forever huge tall')
        gdud

Here’s another

        function Person(name, height){
          // all this stuff becomes part of the object instance when we "new" it
          this.name = name;
          this.height = height;
          this.say = function() {
            console.log(this.name, this.height)
          }
        }
        Person.prototype.saywhat = function() {
          // this lives in the prototype object of the Person
          // the object instance just gets a reference to this via \_\_proto\_\_
          console.log("whaaaat")
        }
    const bro = new Person("brad", "5 ft")
    bro.say()
    bro.saywhat()
    //bro.\_\_proto\_\_
    console.log(bro) // Person { name: 'brad', height: '5 ft', say: [Function] }
    console.log(Person.prototype) // Person { saywhat: [Function]
22
Q

Make an object with a symbol and demonstrate how you can get the value of it

A
let user = {
      name: "eetion",
      type: "dinosaur",
      valid: false,
      age: 9000,
      uniqueId: 1500,
      "testing two": true,
    }
    const uniqueId = Symbol("stuff")
    user[uniqueId] = 1230;
    user[Symbol("lul")] = false;
console.log(user)

console. log(Object.getOwnPropertyNames(user)) // return array of property names as strings
console. log(Object.getOwnPropertySymbols(user)) // return array of symbols
console. log(user[Object.getOwnPropertySymbols(user)[1]]) // get value of item in that array
23
Q

*quickly convert a value to boolean

A

console.log(!!variable)

24
Q

*use a property accessor with bracket notation to assign something to an object property

A
const fun = {
      thing: {
        yes: true,
        no: false
      }["no"]
    }
console.log(fun.thing)
25
Q

use the array.prototype.reduce method and a compose to reduce several functions down to one and work on input

A
function fn1(input) {
      return input + " heh";
    }
    function fn2(input) {
      return input;
    }
    function fn3(input) {
      return input;
    }
    function fn4(input) {
      return input;
    }
    function composeReduce(acc, next) {
      return function(fnInput) {
        return acc(next(fnInput))
      }
    }
const finalFn = [fn1, fn2, fn3, fn4].reduce(composeReduce)

finalFn(1)
        /* alternative */
        // function finalFn(...fns) {
        //   return fns.reduce(composeReduce)
        // }
        //
        // finalFn(fn1,fn2,fn3,fn4)(30)

Using compose to instruct reduce to build a super function which passes input around to each function that composes the super function.

Here’s the code:

   function fn1(fn1input) {
      return fn1input + "person";
    }
    function fn2(fn2input) {
      return fn2input + "you";
    }
    function fn3(fn3input) {
      return fn3input + "there";
    }
    function fn4(fn4input) {
      return fn4input;
    }
    function composeReduce(acc, next) {
      return function(fnInput) {
        return acc(next(fnInput))
      }
    }
const finalFn = [fn1, fn2, fn3, fn4].reduce(composeReduce)

finalFn("hi")

Here’s what reduce does:

Basically, reduce just runs the function for each item in the array, from first to last. The fucntion that it runs is the provided “reducer” function.

[stuff].reduce(provided_reducer_function_here)

The shape of the “reducer” function is as follows, but we just use the mandatory items (previousValue which we call “acc” in our code and currentValue which we call “next” in our code)

Here’s what reduce does for the code provided

First item in the array is Fn1 so that’ll be our acc
Second item in the array is fn2 so that’ll be our next

acc = fn1(fn1input) => input + "person"
next = fn2(fn2input) => input + you"

the reduce operation returns a new acc and we use a new next value

acc = fn1 (fn2(fn2input) => input + "you") => fn1input + "person"
next = fn3(fn3input) => input + "there"

the reduce operation returns a new acc and we use a new next value

acc =  fn1 (fn2(fn3(fn3input) => input + "there") => input + "you") => fn1input + "person"
next = fn4(fn4input) => return fn4input

the reducer operation returns a new acc, which is the final return value

finalFn = fn1 (fn2(fn3(fn4(fn4input) => return fn4input) => input + “there”) => input + “you”) => fn1input + “person”

we pass “hi” as an argument to finalFn

finalFn(“hi”)

fn4 receive “hi”

fn1 (fn2(fn3(fn4(“hi”) => return fn4input) => input + “there”) => input + “you”) => fn1input + “person”

and simply returns it. that return value will be used as input for fn3

fn3 receives “hi”

fn1 (fn2(fn3(“hi”) => input + “there”) => input + “you”) => fn1input + “person”

and returns “hi” + “there” which is “hithere”

fn2 receives “hithere”

fn1 (fn2(“hithere”) => input + “you”) => fn1input + “person”

and returns “hithere” + “you” which is “hithereyou”

fn1 recieves “hithereyou”

fn1 (“hithereyou”) => fn1input + “person”

and returns “hithereyou” + “person” which is “hithereyouperson”

https: //onedrive.live.com/view.aspx?resid=AD38BFAFBDCD692C%211071&id=documents&wd=target%28cp_programmer.one%7C3CACDCA2-E2B9-4995-A587-EC98C052087D%2FUsing%20compose%20to%20instruct%20reduce%20to%20build%20a%20super%20function%7C23660FF6-9CF7-0045-ADFE-C291ADDB3B23%2F%29
onenote: https://d.docs.live.net/ad38bfafbdcd692c/Documents/eetion’s%20Notebook/cp_programmer.one#Using compose to instruct reduce to build a super function&section-id={3CACDCA2-E2B9-4995-A587-EC98C052087D}&page-id={23660FF6-9CF7-0045-ADFE-C291ADDB3B23}&object-id={36898B55-7890-8047-BBD5-9C5DBF7AB393}&28

26
Q

*What does && and || do? And which is executed first?

A

returns the value of the first falsy, so i presume || returns the value of the first truthy?
console.log(“abc” && 10 && NaN && “lol”)

Logical and is executed first:

console.log(“true” && false && true || console.log(“sup”)) // sup \n undefine

27
Q

Explain and demonstrate function currying

A

A currying function is a function that takes multiple arguments one at a time.

Given a function with 3 parameters, the curried version will take one argument and return a function that takes the next argument, which returns a function that takes the third argument. The last function returns the result of applying the function to all of its arguments.

With arity being the number of arguments a function accepts, currying is the process of turning a function with multiplke arity into a function with less arity

const add = a => b => a + b;
    function add(first, second) {
      return first + second;
    }
    const addTwo = add.bind(null, 2)
    addTwo(3)
28
Q

explain and demonstrate memoization

A

Memoization is a programming technique which attempts to increase a function’s performance by caching its previously computed results.

    let cache = {};
        function memoAdd(n) {
          if (n in cache) {
            return cache[n]
          } else {
            console.log('long running calculation happening')
            cache[n] = n + 80;
            return cache[n]
          }
        }
    console. log(memoAdd(5))
    console. log(memoAdd(5))
    console. log(memoAdd(5)

another way:
        const memodat = (function() {
          let cache = {};
          return function(n) {
            if (n in cache) {
              return cache[n]
            } else {
              console.log('long running calculation happening')
              cache[n] = n + 80;
              return cache[n]
            }
          }
        })()
.,
        console.log(memodat(5))
        console.log(memodat(5))
        console.log(memodat(5))
29
Q

explain and demonstrate namespacing

A

Namespacing is when you use a particular name to identify and refer to various items

Example 1:
var $namespace = {}

    Example 2:
    {
        namespace1: {},
        namespace2: {}
    }

https: //flaviocopes.com/javascript-namespaces/
https: //stackoverflow.com/questions/8523231/what-is-meant-by-javascript-namespacing

30
Q

write a script that uses promise.all with async await

A
const promise1 = Promise.resolve(1)
    const promise2 = Promise.resolve(2)
    const promise3 = Promise.resolve(3)
    async function stuff() {
      const values = await Promise.all([promise1, promise2, promise3])
  console.log(values)
}

stuff()
31
Q

write a standard for loop that console.logs the indexes of an array using set timeout with var where the output index shows only the final number, then provide two fixes for it

A

const things = new Array(“bobby”, “billy”, “becky”)

console.log(i, "before the loop")
    // This is one way to encapsulat things
    // results in 0, 1, 2
    // for (let i = 0; i < things.length; i++){
    //   setTimeout(() => {
    //     console.log(i, "inside")
    //   }, 1000)
    // }
    // This is another way to encapsulate things
    // results in 0, 1, 2
    // for (var i = 0; i < things.length; i++){
    //   ((innerEye) => {
    //     setTimeout(() => {
    //       console.log(innerEye, "inside")
    //     }, 1000)
    //   })(i)
    // }
    // And this is the wrong way which doesn't encapsulate things
    // results in all 3's
    for (var i = 0; i < things.length; i++){
      setTimeout(() => {
        console.log(i, "inside")
      })
    }
console.log(i, "after loop")
32
Q

*HOw would you access the first element of an array?

A

Index 0, bracket notation, Array.at()
—————————————————————
const coolarray = [‘1’, ‘2’, ‘3’]

// bracket notation
console.log(coolarray[0])
// using the at method
// according to MDN this is experimental and may change in the future
// doesn't work in IE
console.log(coolarray.at(1))
// using the shift method
// this mutates the array
console.log(coolarray.shift())
// destructuring
const anotherarray = ['1','2','3']
const [billy] = anotherarray
console.log(billy)

const sample = [[‘1’, ‘2,’, ‘3’], [‘4’, ‘5,’, ‘6’]]
let [[a], [b]] = sample;
console.log(a, b); // “1” “4”

—————————————————————
This covers destructuring array
https://www.youtube.com/watch?v=giNjEgYTd9E

33
Q

*How do you create an instance of an object?

A

new keyword using class constructor, Object.create()
—————————————————————
You can use the new keyword to initialize an instance of Object:

const fruits = new Object();

You can use the class keyword to define a new class in JavaScript instead of a function constructor, and then use the new keyword to create an instance of it.

class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
sayHi() {
    return `Hi ${this.name} 👋`;
} }

const user = new User(‘Atta’, 30);

console. log(user.sayHi()); // Hi Atta 👋
console. log(user.age); // 30

The Object.create() method allows us to create a new object, using an existing object as the prototype of the newly created object. This method is especially useful when you want to create a new object from an already existing object.

const Vehicle = {
    maker: 'BMW',
    color: 'Black'
};

const vehicle = Object.create(Vehicle);

console. log(vehicle.maker); // Tesla
console. log(vehicle.color); // Red

34
Q

*Build an old-school for loop and explain it

A

The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.

	    Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.
35
Q

*https://leetcode.com/problems/contains-duplicate/

A

a

36
Q

*https://leetcode.com/problems/valid-anagram/

A

a

37
Q

*https://leetcode.com/problems/fizz-buzz/

A

a

38
Q

*https://leetcode.com/problems/remove-duplicates-from-sorted-array/

A

a

39
Q

https://www.g2i.co/blog/2021-front-end-developer-interview-questions-and-answers

A

asd

40
Q

*make 3 boxes, one inside the other inside the other, center them on the page all of them centered within one another

when you click on one, only that ones event listener runs a console.log showing that ones name. do not trigger the event listener for child that’s in a parent unless you explicitely click on child

A

https: //www.youtube.com/watch?v=XF1_MlZ5l6M
https: //www.youtube.com/watch?v=SqQZ8SttQsI
https: //www.algoexpert.io/frontend/coding-questions/pig-emoji

41
Q

*make the infinite scrol

A

https://www.algoexpert.io/frontend/coding-questions/infinite-scroll

42
Q

*make the navbar

A

https://www.algoexpert.io/frontend/coding-questions/navbar

43
Q

*unscramble the string by removing every third letter without creating a new array:

“Thaisb ics athee tsorngt tnhast oneovear fenadsp, pyeis pito g oeis tone a nd oin amy fari │
enodsi S omae ape opaler s taart edu s inggi ngo itt, nioth kano wi ngo wrhait sith wrash A nda tohe y awipllo cron │ ngOnInit() {
tipnuie tsi ng in g sith fror evtert juustt abelca usle”

A

xport class ArrayChallengeComponent {

inputStr: string = “Thaisb ics athee tsorngt tnhast oneovear fenadsp, pyeis pito g oeis tone a nd oin amy fari enodsi S omae ape opaler s taart edu s inggi ngo itt, nioth kano wi ngo wrhait sith wrash A nda tohe y awipllo cron tipnuie tsi ng in g sith fror evtert juustt abelca usle”;
inputArr: string[];
isBtnDisabled: boolean = false;

  constructor(
    private router: Router
  ) {
    this.inputArr = this.inputStr.split('');
  }
  doReveal() {
    let i = this.inputArr.length;
while (i--) {
  (i + 1) % 3 === 0 && this.inputArr.splice(i, 1);
}

this.inputStr = this.inputArr.join("");
this.isBtnDisabled = true;   }

goNext(): void {
this.router.navigateByUrl(‘where’);
}

—————————————————————

fixIt() {

let input = [ 'T','h','a','i','s','b',' ','i','c','s',' ','a','t','h','e','e',' ','t','s','o','r','n','g','t',' ','t','n','h','a','s','t',' ','o','n','e','o','v','e','a','r',' ','f','e','n','a','d','s','p',',',' ','p','y','e','i','s',' ',     'p','i','t','o',' ','g',' ','o','e','i','s',' ','t','o','n','e',' ','a',' ','n','d',' ',' ','o','i','n',' ','a','m','y',' ',' ','f','a','r','i',' ','e','n','o','d','s','i',' ','S',' ','o','m','a','e',' ','a','p','e',' ','o','p','a','l',       'e','r',' ','s',' ','t','a','a','r','t',' ','e','d','u',' ','s',' ','i','n','g','g','i',' ','n','g','o',' ','i','t','t',',',' ',' ','n','i','o','t','h',' ','k','a','n','o',' ','w','i',' ','n','g','o',' ','w','r','h','a','i','t',' ','s',       'i','t','h',' ','w','r','a','s','h',' ','A',' ','n','d','a',' ','t','o','h','e',' ','y',' ','a','w','i','p','l','l','o',' ','c','r','o','n',' ','t','i','p','n','u','i','e',' ','t','s','i',' ','n','g',' ','i','n',' ','g',' ','s','i','t',       'h',' ','f','r','o','r',' ','e','v','t','e','r','t',' ','j','u','u','s','t','t',' ','a','b','e','l','c','a',' ','u','s','l','e'];

let number = 2;
    input.forEach((letter, index) => {
      if (index === number) {
        input.splice(number, 1)
        number += 2;
      }
    })
return input.join('')   }
44
Q

*walk through my hugo code

A

a

45
Q

*create a fancy search from several api’s

A

see my vim where

46
Q

*make a todo list

A

either this (see my vim)

or this (see that course I just paid for)

47
Q

*make html form and do validation on it

A

find it