npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

tst-expression-transformer

v1.2.2

Published

Expression trees for TypeScript similar to C#.

Downloads

4

Readme

JavaScript(/TypeScript) Expression<> (tst-expression)

NPM version NPM version License: MIT

Readme Card

Expression trees for TypeScript similar to C#.

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

You can compile and run code represented by expression trees. This enables dynamic operations over compiled code, with access to the context captured by the code.

How to Start

  • Install transformer package and ttypescript npm i tst-expression-transformer ttypescript -D,
  • install runtime package npm i tst-expression,
  • update tsconfig.json file,
{
    "compilerOptions": {
        // add tst-expression-transformer plugin
        "plugins": [
            {
                "transform": "tst-expression-transformer"
            }
        ]
    }
}
  • if You use Webpack, updater webpack config,
({
    test: /\.(tsx?)$/,
    loader: "ts-loader",
    options: {
        compiler: "ttypescript"
    }
})
  • write Your code,
  • compile via npx ttsc,
  • run the code.

Expression<>

type Expression<TType> = {
    /**
     * Compiled executable expression.
     */
    compiled: TType;

    /**
     * Expression tree.
     */
    expression: ExpressionNode;

    /**
     * Captured context variables used in expression.
     */
    context: { [capturedVariableName: string]: any };
}

Usage

You can use Expression<> as type of method or function parameters. Transformer tst-expression-transformer handle all calls of those functions and methods and result is the Expression object with AST, compiled expression and captured context used by the expression.

Thanks to runtime package tst-expression, You have typing support with set of type guards, so You can traverse the expression safely.

Simple example, which returns array with name of variable and its value.

import { assertIdentifier, assertExpression, Expression } from "tst-expression";

const someVariable = 5;
const entry = getEntry(someVariable);

console.log(entry); // [ 'someVariable', 5 ]

function getEntry(expression: Expression<number>): [name: string, value: number] {
    assertExpression(expression);
    assertIdentifier(expression.expression);

    return [expression.expression.escapedText, expression.compiled];
}

Example

A little more complex example which takes expression of some math operations and logs the operation with its result.

Result of the example is: someVariable(5) + 5 - PI(3.141592653589793) = 6.858407346410207

import { 
    assertBinaryExpression, assertExpression, Expression, ExpressionKind, ExpressionNode, 
    isBinaryExpression, isNumericLiteral, isIdentifier, isPropertyAccessExpression 
} from "tst-expression";

const someVariable = 5;
logMathOperation(someVariable + 5 - Math.PI);

function logMathOperation(operationExpression: Expression<number>) {
    assertExpression(operationExpression);
    assertBinaryExpression(operationExpression.expression);

    const parts = splitBinaryExpressions(operationExpression.expression);
    let operation = "";

    for (const part of parts) {
        if (typeof (part) == "string") {
            operation += part;
        } else if (isNumericLiteral(part)) {
            operation += part.text;
        } else if (isIdentifier(part)) {
            operation += part.escapedText + `(${operationExpression.context[part.escapedText]})`;
        } else if (isPropertyAccessExpression(part)) {
            if (isIdentifier(part.expression) && isIdentifier(part.name)) {
                operation += part.name.escapedText + `(${operationExpression.context[part.expression.escapedText][part.name.escapedText]})`;
            } else {
                throw new Error("Not implemented.");
            }
        }
    }
    
    console.log(operation, "=", operationExpression.compiled);
}

function splitBinaryExpressions(expression: any): Array<ExpressionNode | string> {
    if (isBinaryExpression(expression)) {
        return [
            ...splitBinaryExpressions(expression.left),
            " " + getOperator(expression.operatorToken) + " ",
            ...splitBinaryExpressions(expression.right)
        ];
    }

    return [expression];
}

function getOperator(operatorToken: ExpressionNode): string {
    return ({
        [ExpressionKind.PlusToken]: "+",
        [ExpressionKind.MinusToken]: "-",
        [ExpressionKind.SlashToken]: "/",
        [ExpressionKind.AsteriskToken]: "*"
    } as { [kind: number]: string })[operatorToken.kind];
}

Transpiled code:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tst_expression_1 = require("tst-expression");
const someVariable = 5;
logMathOperation({ compiled: someVariable + 5 - Math.PI, context: { someVariable, Math }, expression: {
        "flags": 0, "kind": 219, "left": { "flags": 0, "kind": 219, "left": { "flags": 0, "kind": 79, "escapedText": "someVariable" }, "operatorToken": { "flags": 0, "kind": 39 }, "right": { "flags": 0, "kind": 8, "text": "5", "numericLiteralFlags": 0 } }, "operatorToken": { "flags": 0, "kind": 40 }, "right": { "flags": 0, "kind": 204, "expression": { "flags": 0, "kind": 79, "escapedText": "Math" }, "name": { "flags": 0, "kind": 79, "escapedText": "PI" } } } });
function logMathOperation(operationExpression) {
    (0, tst_expression_1.assertExpression)(operationExpression);
    (0, tst_expression_1.assertBinaryExpression)(operationExpression.expression);
    const parts = splitBinaryExpressions(operationExpression.expression);
    let operation = "";
    for (const part of parts) {
        if (typeof (part) == "string") {
            operation += part;
        }
        else if ((0, tst_expression_1.isNumericLiteral)(part)) {
            operation += part.text;
        }
        else if ((0, tst_expression_1.isIdentifier)(part)) {
            operation += part.escapedText + `(${operationExpression.context[part.escapedText]})`;
        }
        else if ((0, tst_expression_1.isPropertyAccessExpression)(part)) {
            if ((0, tst_expression_1.isIdentifier)(part.expression) && (0, tst_expression_1.isIdentifier)(part.name)) {
                operation += part.name.escapedText + `(${operationExpression.context[part.expression.escapedText][part.name.escapedText]})`;
            }
            else {
                throw new Error("Not implemented.");
            }
        }
    }
    console.log(operation, "=", operationExpression.compiled);
}
function splitBinaryExpressions(expression) {
    if ((0, tst_expression_1.isBinaryExpression)(expression)) {
        return [
            ...splitBinaryExpressions(expression.left),
            " " + getOperator(expression.operatorToken) + " ",
            ...splitBinaryExpressions(expression.right)
        ];
    }
    return [expression];
}
function getOperator(operatorToken) {
    return {
        [tst_expression_1.ExpressionKind.PlusToken]: "+",
        [tst_expression_1.ExpressionKind.MinusToken]: "-",
        [tst_expression_1.ExpressionKind.SlashToken]: "/",
        [tst_expression_1.ExpressionKind.AsteriskToken]: "*"
    }[operatorToken.kind];
}

Tip

For work with AST you can use https://astexplorer.net which prints tree nicely. Use the TypeScript AST.

License

This project is licensed under the MIT license.