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

@ts-delight/pipe.macro

v1.0.0

Published

TypeScript friendly fluent pipeline API with support for async steps, additional arguments, early returns and reconciliation

Downloads

4

Readme

About

Babel macro to build pipeline of expressions for more readable left-to-right composition chains.

This plugin supports many niceties like support for awaiting on pipeline steps, support for railway oriented programming, side-effect steps etc. Go through the Features section below for detailed examples.

Example

Source:

import Pipe from '@ts-delight/pipe.macro';

const increment = i => i + 1;
const add = (i, j) => i + j;

const result = Pipe(20)
  .thru(increment)
  .thru(add, 2)();

// Transpiles to:

const increment = i => i + 1;
const add = (i, j) => i + j;

const result = add(increment(20), 2);

Note that the left-to-right composition chain was transpiled to right-to-left composition of plain javascript functions.

Also note that there is no runtime dependency. The import to Pipe macro was entirely compiled away.

Why ?

  1. Left-to-right (or top-to-bottom) logic flow is more readable.
  2. It is nice being able to compose much of logic through expressions (as opposed to a ton of intermediate variables).

This plugin may become obsolete once pipeline-proposal become supported by typescript (Relevant issue). If you don't care about type checking, then you can try out this babel-plugin.

Installation

This utility is implemented as a babel-macro.

Refer babel's setup instructions to learn how to setup your project to use babel for compilation.

  1. Install babel-plugin-macros and @ts-delight/pipe.macro:
npm install --save-dev babel-plugin-macros @ts-delight/pipe.macro
  1. Add babel-plugin-macros to .babelrc (if not already preset):
// .babelrc

module.exports = {
  presets: [
    // ... other presets
  ],
  plugins: [
    'babel-plugin-macros', // <-- REQUIRED
    // ... other plugins
  ],
};

Features

Multi-step chaining:

Multiple levels of invocation can be chained together

Pipe(value)
  .thru(increment) // <- Executed 1st
  .thru(
    i => i - 1 // <- Executed 2nd
  )(); // <- Get result

tap for side-effects:

Pipe(value)
  .thru(increment)
  .tap(i => {
    console.log(i);
  }) // Intercept value without modifying result
  .thru(increment)();

await support:

We can await on results of one step before passing them to another

await Pipe(1) // The pipeline will result in a promise if await is used as a step
  .thru(async i => i + 1)
  .await()
  .thru(j => j + 2)(); // Step after await receives a resolved value and not a promise

await invocations can only be used in contexts where ES7 await is allowed. So following is illegal (and will fail to compile):

const foo = () =>
  Pipe(1)
    .thru(async i => i + 1)
    .await()(); // Await can not be used in a non-async function

Use object methods with tap and thru:

Pipe(new User({id: 1}))
  .tap.register()          // Delegate to method register of User for side effect
  .await()
  .thru.enroll()           // Delegate to method enroll and continue chain with returned value
  .await()
  .thru.assignCourses()

Equivalent to:

(function() {
    const user = new User({id: 1});
    await user.register();                   // Return value discarded            (tap)
    const enrollment = await user.enroll();  // Return value used for next step   (thru)
    return enrollment.assignCourses();
})()

This feature enables you to use third party classes in a fluent manner even if the original author didn't implement a fluent API.

There is atmost one immediately executed function expression generated per pipe, that too is only when side-effects / branching is involved.

Bailing early:

It is possible to have an early-return using bailIf:

Pipe(1)
  .thru(increment)
  .bailIf(i => i === 2) // Predicate to determine if chain should exit early
  .thru(increment) // Operations below are not executed
  .thru(increment)(); // Result is 2

Reconcile bailed results:

We can unify bailed branches and restore pipeline processing through reconcile:

Pipe(1)
  .thru(increment)
  .bailIf(i => i === 2)
  .thru(increment) // Not executed
  .reconcile() // Subsequent pipeline operations will get executed
  .thru(increment)(); // Result is 3

Reconcile can take a function that receives the value (from primary chain or wherever we bailed) and returns a value to be used for subsequent processing

Pipe(1)
  .thru(increment)
  .bailIf(i => i === 2)
  .thru(increment)
  .reconcile(i => ` ${i} `)
  .thru(i => i.trim())(); // Result is "2"

Usage with TypeScript

This library is type-safe and comes with type definitions.

All code must be processed through babel. Compilation through tsc (only) is not supported.

Recommended babel configuration:

// .babelrc

module.exports = {
  presets: [
    '@babel/preset-typescript',
    // ... other presets
  ],
  plugins: [
    'babel-plugin-macros',
    // ... other plugins
  ],
};

Caveats

Every Pipe chain must end with a final function invocation without interruptions.

For example:

const a = 10;
const intermediate = Pipe(a === 10);
const result = intermediate.thru(increment)();

Above code will fail to compile.

Because the entire Pipe chain is compiled away, anything return by Pipe, thru etc. can not be assigned, referenced, or used in any computation.

You may also like:

  1. if-expr.macro: Similar utility, providing a fluent expression-oriented macro replacement for if statement.
  2. switch-expr.macro: Similar utility, providing a fluent expression-oriented macro replacement for switch statement

License

MIT