CLTPayne / reduce

Functional programming challenge to implement reduce() and subsequent array methods without loops or mutation
0 stars 0 forks source link

exercise 3 & 4 #3

Open nicc opened 5 years ago

nicc commented 5 years ago

We're still working with reduce as the basis for recursive list computation.

exercise 3 Implement myFilter this time. Once again using only a single call to myReduce.

exercise 4 Now do myGroupBy. You're still only allowed to implement it using a single call to myReduce. The function should accept a collection and a function. All items in the collection should be grouped by their return value for that function. The return type should be an object / associative list / hashmap / whatever you want to call it. For example:

myGroupBy([1,2,3,4,5,6], (item) => {
    return ( item & 1 ) ? "odd" : "even";
})

should return

{
    "odd": [1,3,5],
    "even": [2,4,6]
}
CLTPayne commented 5 years ago

First attempt going for speed to find a working solution rather than what could be the shortest / most functional perhaps - https://github.com/CLTPayne/reduce/blob/master/filter1.js

Happier with the process as got to a working answer quickly so felt I better understood what needed to happen. (More notes on the process in the README.)

nicc commented 5 years ago

This is perfect. You're not using any state and it's just a simple control-of-flow thing. We just return the accumulating list with or without each item as indicated by the generalised predicate. Nice and simple. Can you see how reduce has made it possible to isolate the transformation step so tersely? If you get used to this way of thinking then all that var i = 0; i++; list[i] stuff is just hideous. It's so extraneous and rickety.

If myGroupBy also goes smoothly then you've probably got the list functions covered tbh.

CLTPayne commented 5 years ago

Looking at exercise 4 - oooooo a bitwise AND. Don't think I've seen this used yet! So to be sure I understand your example function, the conditional in the ternary will always evaluate to either 1 or 0, one being truthy so will return 'odd', zero being falsey so will return 'even'?

CLTPayne commented 5 years ago

https://github.com/CLTPayne/reduce/blob/master/groupBy1.js

It was quick and it works but I'm mutating the accumulator... And it is a bit gross to read with all the accumulator, grouper and item though! Hmmmmm.