FE Interview Test Questions - Approach Flashcards

1
Q

Implement

Promise.all

Implement the Promise.all() function that resolves to an array of result

A
  • return a new promise
    • collect the results in an array - based on the index [p1, p2, p3] - [r1, r2, r3]
    • track if the promises have (un)resolved
    • resolve with empty array if iterable is empty
    • loop over each of the individual promises
      • kick off the promise and await the result
      • assign the result back to the results
      • update the state which tracks if the promises have resolved
      • check if all promises have resolved - if so, then resolve the “new” promise
      • reject the “new” promise if error
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Implement

flatten

Implement a function flatten that returns a newly-created array with all sub-array elements concatenated recursively into a single level.

A
  • loop through array
  • if item is array then spread / flatten (recursive) and add to return array
  • else add item to return array
  • return acc.concat(Array.isArray(item) ? flatten(item) : item)
  • this is recursion, we could do it iteratively
  • create a results array
  • loop over the array to flatten - clone first
    • take first element - shift to remove the element from the clone
    • check if it is array
    • if so, spread the array and add to the start of the cloned array for further checks - unshift
    • else, it’s not an array so push it to the results array
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Implement

filter

Implement Array.prototype.filter.

A
  • loop over the array (this)
  • for each element we want to call the callback func
    • if true, add element to results arr
    • else don’t
  • reduce vs for loop
  • what if the callback func modifes the value? - cache it first
How well did you know this?
1
Not at all
2
3
4
5
Perfectly