https://github.com/youfoundron/babel-plugin-syntax-exists
Allows parsing of an existential check in Babel.
https://github.com/youfoundron/babel-plugin-syntax-exists
Last synced: over 1 year ago
JSON representation
Allows parsing of an existential check in Babel.
- Host: GitHub
- URL: https://github.com/youfoundron/babel-plugin-syntax-exists
- Owner: youfoundron
- Created: 2016-09-01T20:21:27.000Z (almost 10 years ago)
- Default Branch: master
- Last Pushed: 2017-04-08T17:39:07.000Z (over 9 years ago)
- Last Synced: 2024-04-14T09:14:43.874Z (over 2 years ago)
- Language: JavaScript
- Homepage:
- Size: 13.7 KB
- Stars: 6
- Watchers: 4
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Babel Plugin: syntax-exists
This is a Babel plugin which adds syntax for making existential checks in your code.
It uses the the keyword `ex` which is short for *exists*. :sparkles:
[](https://travis-ci.org/rongierlach/babel-plugin-syntax-exists) [](https://david-dm.org/rongierlach/babel-plugin-syntax-exists) [](https://david-dm.org/rongierlach/babel-plugin-syntax-exists#info=devDependencies)
# Features
- [x] Return true if value exists
- [x] Return false if value is null or undefined
- [x] Return child if parent exists
- [ ] Return false on child if parent is null or undefined
- [x] Return function call if value is a function
- [x] Return false for function call if value is not a function
## What?
From The Little Book on Coffeescript:
> Using `if` for `null` checks in JavaScript is common, but has a few pitfalls in that empty strings and `zero` are both coerced into `false`, which can catch you out. CoffeeScript existential operator `?` returns `true` unless a variable is `null` or `undefined`, similar to Ruby's `nil?`.
### So what does it look like?
`foo.ex` transpiles to `typeof foo !== "undefined" && foo !== null`
### How about a more exhilirating use case?
Given an object:
```
let obj = {
attr: 'value',
nested_attr: { name: 'nested' },
func: () => 777
}
```
We can write write the following statements and expect the subsequent returns:
```
obj.ex.attr // 'value'
obj.attr.ex // true
obj.nested_attr.ex.name // 'nested'
// Oh, and it works for functions too...
// --------------------------------------
obj.func.ex // true
obj.func.ex() // 777
// But what about undefined errors?
// --------------------------------------
obj.doesnt_exist.ex // false
obj.doesnt_exist.ex.nope // false, currently unsupported :(
obj.not_a_func.ex() // false
```
## Installation
`$ npm install babel-plugin-syntax-exists`
## Usage
### Via **`.babelrc`** (Recommended)
**babelrc**
```
{
"plugins": ["syntax-exists"]
}
```
### Via CLI
`$ babel --plugins syntax-exists script.js`
### Via Node API
```
require('babel').transform('code', {
plugins: ['syntax-exists']
});
```