JavaScript interpreters don't recognize chains of comparison operators as a linear sequence, but as recursive calls comparing the right-most node and everything to the left of the operator. If a developer wishes to write chained comparison expressions that are linearly evaluated, this plugin is of use.
JavaScript will recursively evaluate the right-most node compared against whatever is on the left.
// written
1 < 6 < 4 < 2 < 7
//evaluated
(1 < 6 < 4 < 2) < 7
((1 < 6 < 4) < 2) < 7
(((1 < 6) < 4) < 2) < 7
// edge case
1 < 2 < 3 < 2 // returns true
//evaluated
(1 < 2 < 3) < 2
((1 < 2) < 3) < 2
(true < 3) < 2 // true coerces to 1
true < 2 // repeated coercion, returns true
Written expressions transformed into linear evaluation
// written
1 < 6 < 4 < 2 < 7
// transformed
1 < 6 && 6 < 4 && 4 < 2 && 2 < 7
// edge case
// written
1 < 2 < 3 < 2
// transformed
1 < 2 && 2 < 3 && 3 < 2 // returns false
$ npm install --save-dev babel-plugin-comparison-chaining
.babelrc
{
"plugins": ["comparison-chaining"]
}
$ babel --plugins comparison-chaining script.js
require('babel-core').transform('code', {
plugins: ['comparison-chaining']
});
MIT