DEV Community

Discussion on: Much needed filterMap in JavaScript

Collapse
 
joelnet profile image
JavaScript Joel • Edited

The same exact logic but written with reduce instead of a for loop.

Array.prototype.filterMap = function(filter) {
  return this.reduce((acc, x, i) => {
    const item = filter(x, i, this);
    if (item !== undefined) {
      acc.push(item)
    }
    return acc
  }, [])
}

more info: Map, Filter, Reduce vs For Loops (syntax)

Also while this function is very cleaver, it is now considered an anti-pattern to modify the prototype of built in objects.

We want to avoid any "smoosh gate" fiasco in the future.

Collapse
 
akashkava profile image
Akash Kava

Well we can have an independent function with array being first parameter. I really don’t care about anti pattern because extending prototype is the best feature of JS. Otherwise everything is possible in other languages

Collapse
 
joelnet profile image
JavaScript Joel

Well we can have an independent function with array being first parameter.

That is what I would recommend

I really don’t care

But see, you should. Something seemingly harmless as extending a prototype has cause much difficulty in the JavaScript community due to name collisions.

An older but popular library extended Array to include flatten. The problem was this version conflicted with the implementation proposed by the TC39. Because the TC39 could not use flatten without breaking the internet, the dumb name smoosh was recommended. github.com/tc39/proposal-flatMap/p...

This has happened multiple times.

Today the TC39 is currently arguing over a name for a global context object. Because node has called their global object global, this name cannot be used without breaking the internet again. So they are currently proposing the horrible name of globalThis github.com/tc39/proposal-global/is...

While your code may have little impact now. It could have very large effects in the future.

So you should definitely care.

Cheers!