Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/nicolo-ribaudo/for-own.macro
A babel-macro that makes for-in only visit own properties
https://github.com/nicolo-ribaudo/for-own.macro
Last synced: 11 days ago
JSON representation
A babel-macro that makes for-in only visit own properties
- Host: GitHub
- URL: https://github.com/nicolo-ribaudo/for-own.macro
- Owner: nicolo-ribaudo
- License: mit
- Created: 2019-02-15T14:42:54.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-03T16:28:15.000Z (almost 2 years ago)
- Last Synced: 2024-10-19T18:46:29.865Z (20 days ago)
- Language: JavaScript
- Size: 293 KB
- Stars: 5
- Watchers: 3
- Forks: 1
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
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:
```js
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](https://github.com/kentcdodds/babel-plugin-macros) 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`](https://github.com/kentcdodds/babel-plugin-macros/blob/master/other/docs/user.md#adding-the-plugin-to-your-config) you can import/requie `import-all.macro`.
Here is an example:
```js
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:
```js
const ownProps = own(obj);
```## LICENSE
MIT