Skip to content

A babel-macro that makes for-in only visit own properties

License

Notifications You must be signed in to change notification settings

nicolo-ribaudo/for-own.macro

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

for-own.macro

A babel-macro that makes for-in only visit own properties


The problem

for ... in statements get enumerable keys from the whole prototype chain. To prevent bugs, it is recommended to write loops like this:

for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    // "key" is a property of "obj"
  }
}

Pretty verbose, right?

This solution

This is a babel-plugin-macro which allows you to iterate only over own keys of an object when using for ... in.

Installation

This module can be installed either with npm or with yarn, and should be installed as one of your project's devDependencies:

npm install --save-dev for-own.macro

# or

yarn add --dev for-own.macro

Usage

Once you have configured babel-plugin-macros you can import/requie import-all.macro.

Here is an example:

import own from "for-own.macro";

for (const key in own(obj)) {
  const value = obj[key];
}

//     ↓ ↓ ↓ ↓ ↓ ↓

for (const key in obj) if (Object.hasOwnProperty.call(obj, key)) {
  const value = obj[key];
}

Caveats

The own macro only works inside for ... in loops. This code will throw an error at compile time:

const ownProps = own(obj);

LICENSE

MIT

About

A babel-macro that makes for-in only visit own properties

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published