I've been challenging myself with solving this in pure functional programming style, in Javascript.
The problem is this:
Input:
var src = [{n:3, x:2}, {n:6, x:1}, {n:2, x:0}, {n:10, x:5}, {n:5, x:2}, {n:1, x:44}];
Problem definition:
Group the items in the src array using a either a predicate or a hash function and sum the item.x values for each group.
For example, in the output I pasted the grouping is the remainder division of item.n with 2
Output:
var trgt = [
{sum:48, items: [{n:3, x:2}, {n:5, x:2}, {n:1, x:44}]},
{sum:6, items: [{n:6, x:1}, {n:2, x:0}, {n:10, x:5}]}
]
The goal here is to find as pure a functional programming solution as possible.
Here is my solution
function moduloTwo(val) {
return (val.n % 2);
}
function makeObjectAndAdd(hashFn) {
return function (result, curr) {
if (result[hashFn(curr)] === undefined) {
result[hashFn(curr)] = {sum: 0, items: []};
}
var newObj = result[hashFn(curr)];
newObj.items.push(curr);
newObj.sum += curr.x;
return result;
};
}
var result = src.reduce(makeObjectAndAdd(moduloTwo), {});
I feel that it could be made to be more "functional".
Thanks!
return !(val%2)since the name infers that it will return a boolean.%3? It wouldn't work withtrue/false. At-least not for this solution. I agree that the function name is misleading though.