Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differentiate between JavaScript Set and immutable Set

I recently ran into an issue where I ended up using the JavaScript Set object without instantiating using the new operator. I use immutable in my project and was expecting to use the Set construct from there, but I forgot to import it.

As expected, the code crashed as the code expected me to write let set = new Set() instead of just let set = Set().

Are there any es-lint rules available that can help in catching such kind of issues?

like image 554
Ashfaque Ahmad Bari Avatar asked Dec 03 '25 10:12

Ashfaque Ahmad Bari


1 Answers

You can add an custom no-restricted-globals rule:

"no-restricted-globals": [
    "error",
    {
        "name": "Set",
        "message": "Use window.Set or add an eslint-ignore if native Set is what you want"
    },
    {
        "name": "Map",
        "message": "Use window.Map or add an eslint-ignore if native Map is what you want"
    }
],

Our project used ImmutableJS inconsistently in the beginning so we ended up with a lot of these issues. One of the worst was when someone migrated code from one file to another and both JavaScript Set and Immutable Set were used. Suddendly untouched code started to fail because an import { Set } from 'immutable'; shadowed the native class.

Two things helped us detect these problems:

  • Whenever we intentionally wanted to use native JavaScript types, we prefixed them with the technically useless, but visually obvious window scope: new window.Set()
  • Since it is a react project, we used prop-types and react-immutable-proptypes on all the components. Never use PropTypes.object though, that rule is almost always true!
like image 106
dube Avatar answered Dec 04 '25 23:12

dube