marko/compiler/ast/ForEach.js
Patrick Steele-Idem 1bf6838c2c Lot's of improvements
All string expressions are now parsed using esprima when using the builder API
2015-12-23 16:47:42 -07:00

64 lines
1.9 KiB
JavaScript

'use strict';
var ok = require('assert').ok;
var Node = require('./Node');
class ForEach extends Node {
constructor(def) {
super('ForEach');
this.varName = def.varName;
this.in = def.in;
this.body = this.makeContainer(def.body);
this.separator = def.separator;
this.statusVarName = def.statusVarName;
ok(this.varName, '"varName" is required');
ok(this.in != null, '"in" is required');
}
generateCode(generator) {
var varName = this.varName;
var inExpression = this.in;
var separator = this.separator;
var statusVarName = this.statusVarName;
var builder = generator.builder;
if (separator && !statusVarName) {
statusVarName = '__loop';
}
if (statusVarName) {
let forEachVarName = generator.addStaticVar('forEachWithStatusVar', '__helpers.fv');
let body = this.body;
if (separator) {
let isNotLastTest = builder.functionCall(
builder.memberExpression(statusVarName, builder.identifier('isLast')),
[]);
isNotLastTest = builder.negate(isNotLastTest);
body = body.items.concat([
builder.ifStatement(isNotLastTest, [
builder.text(separator)
])
]);
}
return builder.functionCall(forEachVarName, [
inExpression,
builder.functionDeclaration(null, [varName, statusVarName], body)
]);
} else {
let forEachVarName = generator.addStaticVar('forEach', '__helpers.f');
return builder.functionCall(forEachVarName, [
inExpression,
builder.functionDeclaration(null, [varName], this.body)
]);
}
}
}
module.exports = ForEach;