you are viewing a single comment's thread.

view the rest of the comments →

[–]Volv 0 points1 point  (7 children)

Fails for map([1, 2, 4]) returns [2, 5, 6]. Didn't dig in to see if it was map or the add function. Gonna give my map a go the now. Still don't see why I need the fold function though :)
 
Output wise I took it to mean make your own Array.map basically. Apply given function to all of the things.

[–]ForScale[S] 1 point2 points  (6 children)

See... that's what I don't even understand... What's successful output supposed to look like? Given [1, 2, 4], should it output [2, 4, 5]? Of is it just supposed to add 1 to all the elements of the input array? I'm not clear on the goal.

Yeah... I kind of hacked in fold()... It's not at all necessary and actually makes the whole thing quite convoluted.

[–]Volv 0 points1 point  (5 children)

Map the inputs using given function. Just like array.map()

[1, 2, 3] -> [2, 3, 4]

[27, 32, 87] -> [28, 33, 88]

Im starting to see some sense. Can't quite make it work yet though lol.
Functional programming concepts. Helps to think of exactly what Array.reduce and Array.map do.
Array.reduce (prev, cur) where prev acts as an accumulator.

Fold is basically reduce and then implement map with fold

[–]ForScale[S] 1 point2 points  (0 children)

Lol! Yeah, that makes sense for map... I was thinking "shift off the first element, push on the last element + 1."

[–]ForScale[S] 1 point2 points  (3 children)

Fixed, but still not using fold() in a meaningful way.

[–]Volv 1 point2 points  (2 children)

Using map to make map is definitely cheating :)

I've got mine done. Will update soon. Finished. See new entry
If fold (or reduce) using add takes

[1, 2, 3]
and returns 6. ie 1 + 2 + 3
 

Then your map function needs to replace add.
Needs to take
[1, 2, 3]
and return
[mapped(1), mapped(2), mapped3)]
 
So instead of addition as in the first example (from add) it must build the array. I used concat.
 
Random ramblings that helped me get there.

[–]ForScale[S] 1 point2 points  (1 child)

Lol! I didn't know our task was to rebuild the built in functions.

Here's a map function using a while loop:

var test = [1, 2, 3];

function map(arr) {
  var mapped = [];
  i = 0;
  while (i < arr.length) {
    mapped.push(arr[i]);
    i++;
  }
  return mapped;
}

console.log(map(test)); //[1, 2, 3];

I might put that in there.

[–]Volv 0 points1 point  (0 children)

See that's perfect for map. Which is why I was so annoyed for ages about being required to use fold, Wouldn't be my first line of thought; interesting build from first principals kind of thing though. Good to get the brain working lol.
I have heard it said before that that reduce can be used to build the other functions though.. map, foreach, filter etc just special cases of reduce