babel-plugin-transform-expressive-loops
Babel plugin to transform enhanced for-in
and for-of
loops.
Comes with added bindings for more terse yet powerful for statements.
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 standardfor(x in y)
(orof
) 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 ( key in object ) statement; for ( item in key in object ) statement; for ( { item_prop } in key in object ) statement; for ( { item_prop } in item in key in object) statement;`
For-Of
for ( item of iterable ) statement; for ( { item_prop } of iterable ) statement; for ( item of index of iterable ) statement; for ( { item_prop } of index in iterable ) statement; for ( { item_prop } of item in index in iterable) statement; for ( comma_delimited_word of List : StringLiteral ) statement; for ( number of Repetitions : IntegerLiteral ) statement;`
Examples
For-In Loops
foritem in key in object objectkey === item; //true foritem_prop in object item_prop === object_key; //true, if _key was available, which it isn't. forfoo bar in item in key in object item === objectkey; foo === itemfoo; bar === itembar; //true
For-Of Loops
foritem of index in iterable item === iterableindex //true forfoo bar of item in index in iterable item === iterableindex; foo === itemfoo; bar === itembar; //true
Convenience Features (Experimental!)
keep in mind, this only works for literal strings and numbers
foritem of i in "foo, bar, baz" const equivalentTo = `foo, bar, baz`; //Note: The split is done at compile time for StringLiteral, otherwise // a split call is returned, for template expressions, as seen here. item === equivalentToi //true fornumber of 3 console // 0 // 1 // 2