Skip to content

Commit

Permalink
feat: Add ExpressionedNode.setExpression
Browse files Browse the repository at this point in the history
  • Loading branch information
dsherret committed Sep 22, 2018
1 parent 532131f commit 12e0ca7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
11 changes: 11 additions & 0 deletions src/compiler/expression/expressioned/ExpressionedNode.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Constructor } from "../../../types";
import { ts } from "../../../typescript";
import { WriterFunction } from "../../../types";
import { Node } from "../../common";
import { Expression } from "../Expression";

Expand All @@ -10,12 +11,22 @@ export interface ExpressionedNode {
* Gets the expression.
*/
getExpression(): Expression;
/**
* Sets the expression.
* @param textOrWriterFunction - Text to set the expression with.
*/
setExpression(textOrWriterFunction: string | WriterFunction): this;
}

export function ExpressionedNode<T extends Constructor<ExpressionedNodeExtensionType>>(Base: T): Constructor<ExpressionedNode> & T {
return class extends Base implements ExpressionedNode {
getExpression() {
return this.getNodeFromCompilerNode(this.compilerNode.expression);
}

setExpression(textOrWriterFunction: string | WriterFunction) {
this.getExpression().replaceWithText(textOrWriterFunction);
return this;
}
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,24 @@ import { getInfoFromTextWithDescendant } from "../../testHelpers";
describe(nameof(ExpressionedNode), () => {
describe(nameof<ExpressionedNode>(n => n.getExpression), () => {
function doTest(text: string, expectedText: string) {
const {descendant} = getInfoFromTextWithDescendant<ParenthesizedExpression>(text, SyntaxKind.ParenthesizedExpression);
const { descendant } = getInfoFromTextWithDescendant<ParenthesizedExpression>(text, SyntaxKind.ParenthesizedExpression);
expect(descendant.getExpression().getText()).to.equal(expectedText);
}

it("should get the correct expression", () => {
doTest("(x + 1)", "x + 1");
});
});

describe(nameof<ExpressionedNode>(n => n.setExpression), () => {
function doTest(text: string, newText: string, expected: string) {
const { descendant, sourceFile } = getInfoFromTextWithDescendant<ParenthesizedExpression>(text, SyntaxKind.ParenthesizedExpression);
descendant.setExpression(newText);
expect(sourceFile.getFullText()).to.equal(expected);
}

it("should set", () => {
doTest("const v = (x + 1)", "y + 2", "const v = (y + 2)");
});
});
});

0 comments on commit 12e0ca7

Please sign in to comment.