Skip to content

Instantly share code, notes, and snippets.

@elsassph
Last active December 5, 2016 23:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elsassph/47c3fb9e6aa59a1ab0a8 to your computer and use it in GitHub Desktop.
Save elsassph/47c3fb9e6aa59a1ab0a8 to your computer and use it in GitHub Desktop.
ES2015 / babel vs Haxe code generation
const a = [1,2,3];
var acc = 0;
for (const v of a) {
acc += v;
}
// want clean code? use Array.reduce
console.log(acc);
var a = [1, 2, 3];
var acc = 0;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = a[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var v = _step.value;
acc += v;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"]) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
console.log(acc);
var a = [1,2,3];
var acc = 0;
// unlike babel, Haxe knows it's an Array<Int> iteration
for (v in a) {
acc += v;
}
trace(acc);
var a = [1,2,3];
var acc = 0;
var _g = 0;
while(_g < a.length) {
var v = a[_g];
++_g;
acc += v;
}
console.log(acc);
@superguigui
Copy link

In ES6 it should be closer to

const a = [1,2,3];
const acc = a.reduce((previous, current) => previous + current);

console.log(acc);

Which compiles nicely to

"use strict";

var a = [1, 2, 3];
var acc = a.reduce(function (previous, current) {
  return previous + current;
});

console.log(acc);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment