DEV Community

Heiker
Heiker

Posted on

What if we had a method on arrays called `.combineWith`?

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])
  ];
};
Enter fullscreen mode Exit fullscreen mode

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" ]
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
gillemic profile image
Michael Gillett

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' ]

Collapse
 
gillemic profile image
Michael Gillett

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 🙂

Collapse
 
vonheikemen profile image
Heiker

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?

Collapse
 
jonyk56 profile image
Jonyk56
  1. no
  2. Absolutely, in fact i just took that code and used it lol
Collapse
 
vonheikemen profile image
Heiker

Nice. I'm curious now, what was the use case?