Nine Pedestrians Mesmerized
    Wondering what’s next for npm?Check out our public roadmap! »

    @thi.ng/dynvar
    TypeScript icon, indicating that this package has built-in type declarations

    0.1.35 • Public • Published

    dynvar

    npm version npm downloads Twitter Follow

    This project is part of the @thi.ng/umbrella monorepo.

    About

    Dynamically scoped variable bindings.

    References:

    Status

    ALPHA - bleeding edge / work-in-progress

    Search or submit any issues for this package

    Installation

    yarn add @thi.ng/dynvar
    // ES module
    <script type="module" src="https://unpkg.com/@thi.ng/dynvar?module" crossorigin></script>
    
    // UMD
    <script src="https://unpkg.com/@thi.ng/dynvar/lib/index.umd.js" crossorigin></script>

    Package sizes (gzipped, pre-treeshake): ESM: 300 bytes / CJS: 354 bytes / UMD: 455 bytes

    Dependencies

    API

    Generated API docs

    TODO - See tests for usage...

    Logging example

    import { dynvar } from "@thi.ng/dynvar";
    import { appendFileSync } from "fs";
    
    interface Logger {
        log(...args: any[]): void;
    }
    
    // create dynamically scoped variable
    // set default/root binding
    const logger = dynvar<Logger>(console);
    
    // dummy function using `logger`
    const foo = () => {
        // deref() returns var's current value
        logger.deref().log("begin foo...");
        for (let i = 0; i < 5; i++) {
            logger.deref().log(i);
        }
        logger.deref().log("foo done.");
    };
    
    foo();
    // (output in console)
    // begin foo...
    // 0
    // 1
    // 2
    // 3
    // 4
    // foo done.
    
    // Alternative Logger impl
    class FileLogger implements Logger {
        constructor(protected path: string) {}
    
        log(...args: any[]) {
            appendFileSync(this.path, args.join(", ") + "\n");
        }
    }
    
    // re-execute `foo` with temporary dynamic scope in which
    // logger is bound to given new value (i.e. here file logger)
    logger.withBinding(new FileLogger("./foo.txt"), foo);
    
    // old scope again (back to using console)
    logger.deref().log("good bye");
    // "good bye"

    Display log file contents:

    cat foo.txt
    # begin foo...
    # 0
    # 1
    # 2
    # 3
    # 4
    # foo done.

    Authors

    Karsten Schmidt

    If this project contributes to an academic publication, please cite it as:

    @misc{thing-dynvar,
      title = "@thi.ng/dynvar",
      author = "Karsten Schmidt",
      note = "https://thi.ng/dynvar",
      year = 2016
    }

    License

    © 2016 - 2021 Karsten Schmidt // Apache Software License 2.0

    Install

    npm i @thi.ng/dynvar

    DownloadsWeekly Downloads

    11

    Version

    0.1.35

    License

    Apache-2.0

    Unpacked Size

    26.7 kB

    Total Files

    10

    Last publish

    Collaborators

    • avatar