Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active July 5, 2022 05:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CMCDragonkai/7d69a9a9f72b0e6f494ac9ebb950af61 to your computer and use it in GitHub Desktop.
Save CMCDragonkai/7d69a9a9f72b0e6f494ac9ebb950af61 to your computer and use it in GitHub Desktop.
TypeScript Let Rec (Asynchronous Recursive Data Structures) #javascript #typescript

Imagine this...

async function main () {
  const config = await (async (
    a = 'a',
    b = 'b',
    c = `${a}/${b}`,
    d = ((
      e = 'e',
      f = ((
        g = a,
      ) => ({
        g,
      }))(),
    ) => ({
      e,
      f,
    }))(),
    h = import('./h'),
    i = d.e,
  ) => ({
    a,
    b,
    c,
    d,
    h: await h,
    i,
  }))();

  console.log(config);
}

main();

This is actually totally possible, and you can run it above in ts-node.

However it's a bit verbose, so maybe if there was some macros to help.

Note that there's no mutual recursion here, and arrow functions are acting as the binders.

Another thing is that it's not really lazy. The promises are asynchronous, but not lazily evaluated.

Would be awesome to have a lazily evaluated DSL for configuration in JS.

Most important thing is that it's completely type-safe, and the lack of mutual recursion means that it's not possible to have infinite loops.

Mutual recursion could still be useful though in some cases.

@CMCDragonkai
Copy link
Author

Another downside is that object keys can be many things, but variable name syntax is limited. Like - is not allowed in the variable name, thus limiting the ability to use this compared to standard object keys.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment