1.2.0 • Published 6 years ago

babel-plugin-transform-for-binding v1.2.0

Weekly downloads
1
License
MIT
Repository
-
Last release
6 years ago

Install

npm install babel-plugin-transform-expressive-loops

.babelrc

{
    "plugins": [
        "transform-expressive-loops"
    ]
}

What does this plugin do?

This plugin allows for the convenient binding of variables commonly associated with iterator loops. For instance, if one wishes to bind the index, item, or a {property} in a single statement, they may do so with this transform.

How does it do that?

This plugin leverages the binary in opperator (e.g. prop in object) in addition to the one already in standard for(x in y) (or of) statements. This plugin won't affect for-statements not clearly using mechanics shown below, given that, it's quite safe. While the used syntax is technically legal in plain ECMAScript, it is otherwise inert or will lead to run-time errors, so there is no risk of collision† or conflation in natural code.

Syntax

The first keyword determines type, in or of, all subsequent keywords are in.

For-In

For-Of

Examples

For-In Loops

for(item in key in object){
    object[key] === item;
    //true
}

for({item_prop} in object){
    item_prop === object[_key];
    //true, if _key was available, which it isn't.
}

for({foo, bar} in item in key in object){
    item === object[key];
    foo === item.foo;
    bar === item.bar;
    //true
}

For-Of Loops

for(item of index in iterable){
    item === iterable[index]
    //true
}

for({foo, bar} of item in index in iterable){
    item === iterable[index];
    foo === item.foo;
    bar === item.bar;
    //true
}

Convenience Features (Experimental!)

keep in mind, this only works for literal strings and numbers

for(item of i in "foo, bar, baz"){

    const equivalentTo = `foo, bar, baz`.split(", ");
    //Note: The split is done at compile time for StringLiteral, otherwise
    //      a split call is returned, for template expressions, as seen here.
    item === equivalentTo[i]
    //true
}

for(number of 3){
    console.log(number)
    // 0
    // 1
    // 2
}

License

MIT License