r/webdev • • Apr 07 '23

How I interview for FE positions

Post image
4.6k Upvotes

668 comments sorted by

View all comments

Show parent comments

43

u/[deleted] Apr 07 '23

Wut, arr.reduce() is used like a thousand times in our codebase for much more complicated shit than summing some numbers . Pretty fair and reasonable question there for summing an array. And I’m saying that as someone who hates live coding.

0

u/[deleted] Apr 07 '23

[deleted]

27

u/OrtizDupri Apr 07 '23

I’ve never used it in 10+ years lol

4

u/Zeilar Apr 08 '23

That's quite shocking, not even once? I have used it probably a few dozen times already in roughly 5 years since I first started studying programming.

0

u/[deleted] Apr 07 '23

[deleted]

9

u/ShijinModan Apr 07 '23

Reducers are a tool in state management and not the same things as an array reduce. The latter is a function that is called for each element in the array to reduce it to a single value. The former is a function that accepts a state object and returns a new one.

3

u/TehCheator Apr 08 '23

They're conceptually the same, however, that's why reducers are called reducers.

The callback (reducer) is a function that accepts an accumulator (state object) and a value from an array (update message), then uses those inputs in some way to return a new accumulator (state object). The return value is then used as the input to the next iteration with the next array value (update message).

It's a pattern from functional programming to model state management as a reduce operation on an infinite series of updates.

3

u/Zeilar Apr 08 '23

Why focus on the reduce example? You can just as well do this with for loops, and the way you'd write this function with a for loop is a very basic and common way of making a sum of something.

Either way no developer should have any issue writing the sum function in OP's post. If you need to look that up as a paid developer, I'm sorry to say that you're in the wrong business.

2

u/theQuandary Apr 07 '23

I doubt they'd care if you did a for loop either (though I'd expect a follow-up question to make sure I understood closures and higher-order programming).

7

u/athaliah Apr 07 '23

I've rarely used it in 10+ years because I don't often work with numbers. I will remember what it does for the next 20 minutes and then that knowledge will disappear into the black hole that is my brain.

11

u/mcaruso Apr 07 '23

reduce is used for more than just numbers, you can use it to construct anything. It's basically the functional programming equivalent of a (generalized) for loop (although usually you'd use something more specific like map/flatMap/filter).

5

u/theQuandary Apr 07 '23

.reduce() is used for more than numbers.

Any time you want an array item to turn into on item that combines them, this is probably worth considering.

Let's do some examples with the classic person object (here's a TS definition). All of these could be done with a for loop, but aren't possible with the more popular .filter() or .map() functions.

interface Person {
  firstName: string
  lastName: string
  age: number
  address: string
}

Let's group everyone by last name. Note that acc is short for accumulator and is a fairly popular convention that represents whatever state you are saving between iterations.

const peopleByLastName = people.reduce(
  (acc: {[key: string: Person[]}, person: Person) => {
    //create the person array if it doesn't exist
    if (!acc[person.lastName]) acc[person.lastName] = []
    //add a person to the list
    acc[person.lastName].push(person)
    //return the list so we can use it again
    return acc
  }, {})

Here's a more complex example of finding the person/people with the longest name.

// get the length of the person's name.
const nameLength = (person: Person): number => 
  person.firstName.length + person.lastName.length

const longestNames = people.reduce((acc, person: Person) => {
  const length = nameLength(person)
  if (length > acc.length) {
    acc.person = [person]
  } else if (length === acc.length) {
    acc.person.push(person)
  }
  return acc
}, {length: 0, person: []}).person

Here's a max function that works on objects rather than just an array of numbers. This is a very classic example of reducing across a list.

function max<T>(fn: (items: <T>[]) => number, list) =>
  list.reduce((acc, item:<T>) => Math.max(fn(item), acc))

let oldest = max<Person>(person => person.age, people)

Another classic example is counting how many items match. You could do this with a .filter(), but you would wind up creating a whole new list just to find out how many while this just creates a single number.

function count<T>(fn: (items: <T>[]) => boolean, list) => list.reduce((acc, item:<T>) => fn(item) ? acc + 1 : acc, 0)

let retired = count<Person>(person => person.age > 67), people)

We now have flat, but in times past, reduce used to be the best way to implement this.

3

u/Triptcip Apr 07 '23

If it's of any help, it doesn't have to be used for numbers. Have you had times where you push items into an array when looping over something? Well you can use reduce instead.

You might be familiar with this pattern of pushing items into an array that is defined outside the scope of the loop.

const myArray = [] 
[1,2,3].forEach(val => {
  myArray.push(val)
})

console.log(myArray) // [1,2,3]

Well you can use reduce here instead

const myArray = [1,2,3].reduce((accumulator, val) => {
  accumulator.push(val)

  return accumulator
}, [])

console.log(myArray) // [1,2,3]

0

u/[deleted] Apr 08 '23

[deleted]

1

u/Triptcip Apr 08 '23

Well not a great example because the starting array is the same as the output so you technically don't even need a map.

It was just to demonstrate that the common pattern of using push inside an iterater can be replaced with reduce

2

u/SoBoredAtWork Apr 08 '23

What do you use it for besides summing numbers? It's perfect for summing, but any other time I've seen a dev use it for something else, it's always been over engineered or just adds complexity and makes code harder to read.

0

u/[deleted] Apr 08 '23

[deleted]

1

u/hanoian Apr 08 '23

This would read nicer if you returned the #000 on line 44 before the reduce by doing a <= check first.

2

u/scyber Apr 08 '23

IME, Array.reduce() is one of the most useful array methods, that has the fewest use cases. The question posted above is the perfect use case for it. But I have spoken to FE devs that have a decent amount of experience that may have used it once or twice at most in their careers. And for them, it may not be the first thing that pops into their minds when they see a problem that requires a loop.

I worked at a company that had a coding challenge with a very similar question. It was summing two arrays and returning the higher one. Reduce was the perfect method for that. But from running the interview a few dozen times we realized what I posted above. That it isn't the first thing that comes to mind sometimes. As such, we updated the scoring rubric to not deduct points for interviewees that didn't use reduce in the first pass. Usually during the refactor stage many noticed it, but not all. It is just a pattern that isn't used as often for many FE devs.

1

u/GreatValueProducts Apr 07 '23

It is also a very common way to convert from array to map other than Object.fromEntries.