feat(transpiler): implement optional params

This commit is contained in:
vsavkin 2014-10-02 12:04:41 -04:00 committed by Vojta Jina
parent fb01551620
commit 1214f423b4
2 changed files with 48 additions and 0 deletions

View File

@ -36,5 +36,22 @@ export function main() {
expect(f()).toBe(3); expect(f()).toBe(3);
}); });
}); });
describe("optional params", function () {
it("should work", function () {
function optional(a=1,b=2){return a + b;}
expect(optional()).toEqual(3);
expect(optional(10)).toEqual(12);
expect(optional(10, 20)).toEqual(30);
});
it("should support a mix of optional and mandatory params", function () {
function optional(a,b=2){return a + b;}
expect(optional(1)).toEqual(3);
expect(optional(10)).toEqual(12);
});
});
}); });
} }

View File

@ -3,6 +3,7 @@ import {
AT, AT,
CLOSE_CURLY, CLOSE_CURLY,
CLOSE_PAREN, CLOSE_PAREN,
CLOSE_SQUARE,
COLON, COLON,
COMMA, COMMA,
EQUAL, EQUAL,
@ -10,6 +11,8 @@ import {
IMPORT, IMPORT,
OPEN_CURLY, OPEN_CURLY,
OPEN_PAREN, OPEN_PAREN,
OBJECT_PATTERN,
OPEN_SQUARE,
SEMI_COLON, SEMI_COLON,
STAR, STAR,
STATIC STATIC
@ -118,6 +121,34 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
this.visitAny(tree.body); this.visitAny(tree.body);
} }
visitFormalParameterList(tree) {
var hasPosOptionalParams = false;
var first = true;
for (var i = 0; i < tree.parameters.length; i++) {
var parameter = tree.parameters[i];
if (first) {
first = false;
} else {
this.write_(COMMA);
this.writeSpace_();
}
if (!hasPosOptionalParams && this._isOptionalPositionParam(parameter.parameter)) {
hasPosOptionalParams = true;
this.write_(OPEN_SQUARE);
}
this.visitAny(parameter);
}
if (hasPosOptionalParams) {
this.write_(CLOSE_SQUARE);
}
}
_isOptionalPositionParam(parameter) {
return parameter.initializer && parameter.binding.type !== OBJECT_PATTERN;
}
/** /**
* @param {PropertyMethodAssignment} tree * @param {PropertyMethodAssignment} tree
*/ */