Just... you know a generic way of smashing all the items on an array into one. Like, you give it a "combiner" function to .combineWith
and it will just apply that to everything.
Imagine this situation. You have custom data type you work with. Maybe a weird tuple to keep this example simple. You know at some point you want to combine those things, so you make a function.
function combine_tuples(tuple_a, tuple_b) {
return [
tuple_a[0] + tuple_b[0],
tuple_a[1].concat(', ', tuple_b[1])
];
};
Now in your awesome app you receive an array of these weird tuples. You want to smash these things together, what do you do? You use .combineWith
and your "combiner function".
const some_tuples = [
[10, 'Awesome'],
[4, 'Okay-ish'],
[2, 'Oh hell no']
];
some_tuples.combineWith(combine_tuple);
// => [ 16, "Awesome, Okay-ish, Oh hell no" ]
To you, dear reader who thinks there is something fishy in my example (and this whole post), my question to you is this: would you think this method is so horrible that you would create a lint rule to avoid it at all cost in your codebase?
And you, dear reader who is intrigued by this "non-existent" method:
- Do you think this method does too much?
- Would you use this?
Top comments (5)
I was able to achieve the same result using the reduce method.
const some_tuples = [
[10, "Awesome"],
[4, "Okay-ish"],
[2, "Oh hell no"]
];
function combine_reducer(tuple_a, tuple_b) {
return [
tuple_a[0] + tuple_b[0],
tuple_a[1].concat(', ', tuple_b[1])
]
}
console.log(some_tuples.reduce(combine_reducer));
running this through node gave me:
$ node combine_with.js
[ 16, 'Awesome, Okay-ish, Oh hell no' ]
Seems similar to the
.reduce()
function in javascript. Although I don't know enough about .reduce() to know if your example would be attainable using it alone. Either way, good job on making a function and sharing it with us 🙂Yes. It is exactly what
reduce
is good for. I'm trying an experiment in this post. Just to see what people think. Like what if it had a another name? Would they still hate it, to do the point of making a linting rule that won't let you ship code with it?Nice. I'm curious now, what was the use case?