From 1214f423b41e65a4cb5b382eac22d9cd378faa14 Mon Sep 17 00:00:00 2001 From: vsavkin Date: Thu, 2 Oct 2014 12:04:41 -0400 Subject: [PATCH] feat(transpiler): implement optional params --- tools/transpiler/spec/functions_spec.js | 17 ++++++++++ .../outputgeneration/DartParseTreeWriter.js | 31 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/tools/transpiler/spec/functions_spec.js b/tools/transpiler/spec/functions_spec.js index fad983e609..ec409cb2d7 100644 --- a/tools/transpiler/spec/functions_spec.js +++ b/tools/transpiler/spec/functions_spec.js @@ -36,5 +36,22 @@ export function main() { 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); + }); + }); }); } diff --git a/tools/transpiler/src/outputgeneration/DartParseTreeWriter.js b/tools/transpiler/src/outputgeneration/DartParseTreeWriter.js index e1f76af7cd..94cf6c45f0 100644 --- a/tools/transpiler/src/outputgeneration/DartParseTreeWriter.js +++ b/tools/transpiler/src/outputgeneration/DartParseTreeWriter.js @@ -3,6 +3,7 @@ import { AT, CLOSE_CURLY, CLOSE_PAREN, + CLOSE_SQUARE, COLON, COMMA, EQUAL, @@ -10,6 +11,8 @@ import { IMPORT, OPEN_CURLY, OPEN_PAREN, + OBJECT_PATTERN, + OPEN_SQUARE, SEMI_COLON, STAR, STATIC @@ -118,6 +121,34 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter { 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 */