{"id":13673276,"url":"https://github.com/luvies/lazy","last_synced_at":"2025-04-28T09:30:28.884Z","repository":{"id":34136380,"uuid":"169793303","full_name":"luvies/lazy","owner":"luvies","description":"A linq-like lazy-evaluation enumerable/iteration library that aims to support deno, node \u0026 browser","archived":true,"fork":false,"pushed_at":"2022-04-10T03:07:35.000Z","size":968,"stargazers_count":32,"open_issues_count":7,"forks_count":3,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-15T20:01:55.406Z","etag":null,"topics":["browser","deno","denoland","enumerable","enumeration","iteration","iterator","lazy","linq","node","node-js","nodejs"],"latest_commit_sha":null,"homepage":"https://luvies.github.io/lazy/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/luvies.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-02-08T20:17:16.000Z","updated_at":"2025-02-17T20:43:54.000Z","dependencies_parsed_at":"2022-08-08T00:01:23.166Z","dependency_job_id":null,"html_url":"https://github.com/luvies/lazy","commit_stats":null,"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luvies%2Flazy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luvies%2Flazy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luvies%2Flazy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/luvies%2Flazy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/luvies","download_url":"https://codeload.github.com/luvies/lazy/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251026836,"owners_count":21525041,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["browser","deno","denoland","enumerable","enumeration","iteration","iterator","lazy","linq","node","node-js","nodejs"],"created_at":"2024-08-02T10:00:32.439Z","updated_at":"2025-04-28T09:30:28.011Z","avatar_url":"https://github.com/luvies.png","language":"TypeScript","readme":"# Lazy Iteration\n\n[![Build Status](https://travis-ci.com/luvies/lazy.svg?branch=master)](https://travis-ci.com/luvies/lazy) ![Github Build Status](https://github.com/luvies/lazy/workflows/Node%2FDeno%20CI/badge.svg) [![npm version](https://badge.fury.io/js/%40luvies%2Flazy.svg)](https://badge.fury.io/js/%40luvies%2Flazy)\n\nThis module is meant to provide memory-efficient lazy-evaluation iteration for iterable objects. The aim of this project is to support deno, node and browser, and support all native JavaScript systems for iteration (for-of, for-await-of, etc).\n\n## Contents\n\n- [Installation](#installation)\n  - [Deno](#deno)\n  - [Node](#node)\n- [Overview](#overview)\n- [Examples](#examples)\n- [Introp with native](#interop-with-native)\n- [API](#api)\n  - [Promises](#promises)\n  - [No additional unexpected iteration](#no-additional-unexpected-iteration)\n  - [Custom implementations](#custom-implementations)\n  - [Compatibility](#compatibility)\n  - [Shorthand usage](#shorthand-usage)\n- [Setting up this project](#setting-up-this-project)\n- [Footnotes](#footnotes)\n\n## Installation\n\n### Deno\n\nUse the following import:\n\n```ts\nimport { Lazy } from 'https://deno.land/x/lazy@v{version}/lib/mod.ts';\n```\n\nMake sure the `@v{version}` tag is the correct one you want. I'd recommend against master, as it could change without notice \u0026 might be broken (although I will try not to break it).\n\n### Node\n\nThe packge can be found here: https://www.npmjs.com/package/@luvies/lazy.\n\nInstall via\n\n```\nyarn add @luvies/lazy\n```\n\nor\n\n```\nnpm install @luvies/lazy\n```\n\nImport using\n\n```ts\nimport { Lazy } from '@luvies/lazy';\n```\n\nor\n\n```js\nconst { Lazy } = require('@luvies/lazy');\n```\n\n## Overview\n\nAt a base level, this module provides the following exports:\n\n```ts\nabstract class Lazy\u003cTElement\u003e {...}\n\n// These are provided to allow direct imports, but are just aliases over the static class methods.\nfunction from\u003cTElement\u003e(iterable: Iterable\u003cTElement\u003e): Lazy\u003cTElement\u003e;\nfunction empty\u003cTElement\u003e(): Lazy\u003cTElement\u003e;\nfunction range(start: number, end?: number): Lazy\u003cnumber\u003e;\nfunction repeat\u003cTElement\u003e(element: TElement, count?: number): Lazy\u003cTElement\u003e;\n```\n\nThe `Lazy` class is the root of the module, all things come from it and are derived off it. To start using it, do something like the following:\n\n```ts\n// Static method import.\nimport { Lazy } from 'https://deno.land/x/lazy@v{version}/lib/mod.ts';\n\nconst iterable = Lazy.from([1, 2, 3, 4, 5]);\n\n// Direct function import.\nimport { from } from 'https://deno.land/x/lazy@v{version}/lib/mod.ts';\n\nconst iterable = from([1, 2, 3, 4, 5]);\n```\n\nAfter you have done this, the full power of the module is available to play with.\n\n## Examples\n\nThe aim of the module is to support the full suite of Linq methods the C# provides, as it covers a large surface area with the possible use-cases. Not only does it aim to provide them, it aims to act like them. Nothing is is executed until you call the iterator and start walking through the elements of the list. Here's a small example:\n\n```ts\nconst evenSquares = Lazy.range(0, 1000)\n  .where(i =\u003e i % 2 === 0)\n  .select(i =\u003e i ** 2);\n```\n\nThe result of this chain is an iterator object, however nothing has actually happened yet. As with linq, things only happen exactly when you ask for it:\n\n```ts\nfor (const num of evenSquares) {\n  console.log(num); // 0, 4, 16, 36, 64, 100, 144...\n}\n```\n\nA huge part of what makes linq so powerful is its composability, which this module provides at a base level:\n\n```ts\nconst selectedEvenNumbers = evenNumbers.take(10);\n```\n\nAs with C# Linq, this statement will create a new iteratable object that only returns the first 10 elements of the original iterable object. And the order of composability is not limited, every single method that returns an iterator supports chaining with every other method. On top of this, this module supports the same linq aggregation functions that linq does, for example:\n\n```ts\nconsole.log(selectedEvenNumbers.sum()); // -\u003e 1140\n```\n\nThese functions allow you to deal with iterable objects at a high-level, hiding the fact that not all of the values might be available until the iteration is actually done. They also handle things like short-cuts, for example:\n\n```ts\nconsole.log(Lazy.range(0, 1000).any(i =\u003e i \u003e 100)); // -\u003e true\n```\n\nThis function knows that as soon as the condition is fulfilled, it can stop iterating and hand back the result, saving time with iterating the entire list (which would be easy to forget otherwise).\n\nA primary aim of this library is to allow complex transformations on large datasets without having to deal with the copying that JavaScript normally does, for example:\n\n```ts\nconst data = getData(); // Could be a large list of datapoints.\n\n// Native JS\nconst points = data\n  .map(d =\u003e d.x)\n  .filter(x =\u003e selectPoint(x))\n  .map(x =\u003e adjustPoint(x));\nconst avg = points.reduce((prev, curr) =\u003e prev + curr) / points.length;\n\n// Lazy iterators\nconst avg = Lazy.from(data)\n  .select(d =\u003e d.x)\n  .where(x =\u003e selectPoint(x))\n  .select(x =\u003e adjustPoint(x))\n  .average();\n```\n\nThe native version will create 3 copies of the array, non of which are used beyond the last to calculate the final average, after which point it is also usless. In contrast, the lazy iterator will only apply the transformations/filters at the exact point they are needed, so no copies are done, and the built-in aggregation function allow for a nicer final calculation.\n\n## Interop with native\n\nWhile all of these functions are good, it would be difficult to integrate them without being about to easily convert back to native JS objects. Fortunately, this module provides just that. Currently there are 2 functions, `toArray` and `toMap`, which do pretty much exactly as they seem. You can end a lazy chain with one of these to make it resolve all of the iterators and output a native JS object, which can be then used in consuming code.\n\nOn top of this, the entire module is build upon the native JS iteration protocol, meaning that any object that implements that can be used with it with no other changes. Just drop the object into a `Lazy.from(...)` call, and everything will be available.\n\nThe `Lazy` class is also JSON-serialisable (as a list), meaning that you can simply pass the result of a chain into `JSON.stringify` and it will stringify correctly.\n\n## API\n\nVisit https://luvies.github.io/lazy/ for the full documentation.\n\nFor an overview of the reference I use for developing this module, visit the [.NET Linq docs](https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable).\n\nAs an aside, all of the functions exported from [aggregates.ts](lib/aggregates.ts) support taking in any object that implements the `Iterator\u003cT\u003e` iterface, so you can use them without wrapping the iterable around `Lazy` first if you so wish (although I'd recommend using them through `Lazy`).\n\n### Promises\n\nThis module fully supports promises, and things like for-await-of. As an example (taken from the tests):\n\n```ts\nconst list = [\n  Promise.resolve(1),\n  Promise.resolve(2),\n  Promise.resolve(3),\n  Promise.resolve(4),\n  Promise.resolve(5),\n];\n\nfor await (const element of Lazy.from(list)) {\n  console.log(element);\n}\n\n/*\n  Output:\n\n  -\u003e 1\n  -\u003e 2\n  -\u003e 3\n  -\u003e 4\n  -\u003e 5\n*/\n```\n\nHowever, it also supports resolving all promises in the iterable to their values all at once, using the help of `Promise.all`:\n\n```ts\nconst list = [\n  Promise.resolve(1),\n  Promise.resolve(2),\n  Promise.resolve(3),\n  Promise.resolve(4),\n  Promise.resolve(5),\n];\n\nfor (const element of (await Lazy.from(list).resolveAll()).select(\n  i =\u003e i ** 2,\n)) {\n  console.log(element);\n}\n\n/*\n  Output:\n\n  -\u003e 1\n  -\u003e 4\n  -\u003e 9\n  -\u003e 16\n  -\u003e 25\n*/\n```\n\nFor TypeScript users, the `resolveAll` function all also correctly determines the resulting object type, even if there is a mix of promises and non promises:\n\n```ts\nconst list = [\n  Promise.resolve(1),\n  2\n  Promise.resolve(3),\n  4\n  Promise.resolve(5),\n]; // type -\u003e Array\u003cnumber | Promise\u003cnumber\u003e\u003e\n\nLazy.from(list).resolveAll() // type -\u003e Promise\u003cLazy\u003cnumber\u003e\u003e\n```\n\n### 'No additional unexpected iteration'\n\nFor any function on `Lazy` that uses this term, it simply means 'if you start iteration on the resulting object, it will not perform any iteration you did not ask for'. To put it another way, when you call the iterator function, nothing will happen until you explicitly ask for the next element. This term is used since, for some functions, additional iteration is needed in order to perform the action required. An example of this would be the `reverse` method; you cannot iterate the first element of the result until you know what the last element of the underlying iterable is, so it has to iterate it completely first before returning the first element. In contrast, the `select` method will only iterate to the next element when you ask it to, thus it doesn't perform any additional unexpected iteration.\n\n### Custom implementations\n\nThis module supports using your own lazy iterable implementations in the chain. This is because of the way all of the functions are implemented, which is that they return a new object that extends the `Lazy` class and only contains the exact properties needed to perform the iteration. This allows you to write a custom implementation that does something unique to the problem you need to solve, and then integrate it into the normal chain. Here is an example implementation:\n\n```ts\nclass LazyToString\u003cTSource\u003e extends Lazy\u003cstring\u003e {\n  public constructor(private readonly _iterable: Iterable\u003cTSource\u003e) {\n    super();\n  }\n\n  public *[Symbol.iterator](): Iterator\u003cstring\u003e {\n    for (const element of this._iterable) {\n      yield `${element}`;\n    }\n  }\n}\nconst iterableToString = \u003cTSource\u003e(t: Iterable\u003cTSource\u003e) =\u003e new LazyToString(t);\n\nconst result = Lazy.from([1, 10, 100, 1000])\n  .apply\u003cLazyToString\u003cnumber\u003e, string\u003e(iterableToString)\n  .select(s =\u003e s.length)\n  .toArray();\n\n// result -\u003e [1, 2, 3, 4]\n```\n\nObviously this is a contrived example, since the same could be done with a single `select`, but you see the power that is available. You can make any custom implementation at all, and it will chain as if it was part of the API itself.\n\n### Shorthand usage\n\nIf you are using `Lazy.from` a lot in your code, you can use the following snippet to make usage much more ergonomic:\n\n```ts\ndeclare global {\n  interface Array\u003cT\u003e {\n    /**\n     * Returns the lazy iterator of the current array.\n     */\n    lazy: Lazy\u003cT\u003e;\n  }\n}\n\nObject.defineProperty(Array.prototype, 'lazy', {\n  get() {\n    return Lazy.from(this);\n  },\n});\n```\n\n## Setting up this project\n\nThis project is written primarily for deno, with node support being done via a 2-step compilation process. In order to set up the project, you need to install [deno](https://github.com/denoland/deno) globally. To make editing work in VSCode, make sure that you do the following:\n\n- Run `yarn` to install the dependencies that VSCode needs to edit properly\n- Run `yarn init-types` to grab the types for the testing module\n- Make sure that VSCode is using the local TypeScript version (bottom right of the editor while opening a `.ts` file)\n- Adjust the [`tsconfig.json`](tsconfig.json) so that the `paths` are pointing to the right directory\n  - They should point to the `$HOME/.deno/deps/http` and `$HOME/.deno/deps/https` directories\n  - The path has to be relative due to a TS server limitation\n  - _DO NOT COMMIT THIS CHANGE_, as it only applies to your setup and your setup only\n\n### Compatibility\n\nAs mentioned before, this module is fully compatible with normal ES2015 iterators and native arrays/maps. It targets ES2015, meaning that if you need to support ES5 \u0026 earlier, you will need to use a transpiler like babel. For Node.js, it requires about v6 or higher (not properly tested on this version though).\n\n## Footnotes\n\nMassive thanks to the .NET Core team and their work on Linq, the source reference was invaluable when implementing some of the methods here.\n","funding_links":[],"categories":["基础设施","Uncategorized","Modules"],"sub_categories":["JAM Stack/静态站点","Uncategorized","Online Playgrounds","Utils","Assistants"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluvies%2Flazy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fluvies%2Flazy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fluvies%2Flazy/lists"}