Iterables, streams for typescript

Overview

Iterable for Typescript

Similar to what we know from C#, Dart or any other language which supports them, we use Iterables to stream over collections.

Why using the Iterable?

Iterables are useful when you want to chain several operations on a collection such as

  • filter
  • filterNotNull
  • group
  • sort
  • map
  • mapNotNull
  • take
  • skip
  • every
  • none
  • some
  • etc ...

For example, lets consider a case. We need to work with a collection to filter the numbers greater than 20, map to the string only the 3'rd value.

  • Without the Iterable
const data = [1, 10, 20, 30, 40, 50, ...];
const filteredData = data.filter(x => x > 20);
const value = filteredData[3];
const mappedValue = value.toString();

// result "50"
  • Using the Iterable
const data = [1, 10, 20, 30, 40, 50, ...];
const mappedValue = asIterable(data)
    .filter(x => x > 20)
    .skip(2)
    .map(x => x.toString())
    .first()

// result "50"

The Iterable code would be similar as

let skipped = 0;
for (let i = 0; i < data.length; i++) {
    const element = data[i];
    if (element > 20 && ++skipped < 2) return element.toString();
}
throw new NoElementError();

Not only the difference stays that we have written it differently, but also how much data was processed.

On the example without using the Iterable

  • All elements of the collection are visited and filtered
  • The third element is retrieved
  • The retrieved element is mapped to a string

Now, if the collection is really huge, this will take time to process.

While, using the Iterable, that is not necessarily as we know we do not need all the elements. Because we call first() at the end, that means that the operation will stop as soon this condition is meet.

  • Find from collection only the first value that is greater than 20
  • Map the value to a string

Installation

npm i @xeinebiu/ts-iterable

Examples

Convert a list to iterable

const data = [1, 2, 3, 4, 5];
const iterable = asIterable(data);

Filter

// without the Iterable
const filtered = data.filter(x => x < 4);

// with iterable
const filtered = asIterable(data)
    .filter(x => x < 4)
    .toList();

// result [1, 2, 3]

Filter Not Null

Filter undefined|null values out

const data = [1, 2, null, 3, undefiend, 4];
const filtered = asIterable(data)
    .filterNotNull();

// result [1, 2, 3, 4]

Take

Take specific amount of elements

// without iterable
const taken = data.slice(0, 3);

// with iterable
const taken = asIterable(data)
    .take(3)
    .toList();

// result [1, 2, 3]

Every

Return true if all elements match the predicate.

const result = asIterable(data)
    .every(x => x.toString() !== "hello world");

// result true

Some

Return true if any of the elements match the predicate

const result = asIterable(data)
    .some(x => x.toString() !== "1");

// result true

None

Return true if all the elements do not match the predicate

const result = asIterable(data)
    .none(x => x <= -1);

// result true

First

Return the first element if available, otherwise throw NoElementError

const result = asIterable(data)
    .filter(x => x > 4)
    .first();

// result 5

First Or Null

Return the first element if available, otherwise null.

const result = asIterable(data)
    .filter(x => x > 100)
    .firstOrNull();

// result null

Map

Map the elements using a mapper

const result = asIterable(data)
    .filter(x => x < 3)
    .map(x => x.toString())
    .toList();

// result ["1", "2"]

Map Not Null

Map the elements using the mapper and avoid inserting null|undefined values in the list

const data = [1, null, 2, undefined, 3];

const result = asIterable(data)
    .filter(x => x < 3)
    .mapNotNull(x => x?.toString())
    .toList();

// result ["1", "2", "3"]

Skip

Offset the elements cursor starting from index 0

const result = asIterable(data)
    .skip(1)
    .toList();

// result ["2", "3", "4", "5"]

Take

Take specific amount of elements

const result = asIterable(data)
    .take(2)
    .toList();

// result ["1", "2"]

Sort

Sort all elements and return new [ExtendedIterable]

const sorted = asIterable(data)
    .sort((a, b) => b - a)
    .toList();

// result [5, 4, 3, 2, 1]

Group

Group all elements and return new [ExtendedIterable]

const data = [-9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

const groupedData = asIterable(data)
    .group(x => {
        if (x < 0) return "negative";
        return "positive";
    })
    .toList();

// result
// [
//     ["negative", [-9, -8, -7, -6, -5, -4, -3, -2, -1]],
//     ["positive", [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
// ];

To List

Convert the Iterable to a collection.

const list = asIterable(data)
    .toList();

// result [1, 2, 3, 4, 5]

MIT

The MIT License

License: MIT

You might also like...

typescript-to-jsonschema generates JSON Schema files from your Typescript sources.

fast-typescript-to-jsonschema English | 简体中文 a tool generate json schema from typescript. Feature compile Typescript to get all type information conve

Nov 28, 2022

Convert some JavaScript/TypeScript code string into a .d.ts TypeScript Declaration code string

convert-to-dts Converts the source code for any .js or .ts file into the equivalent .d.ts code TypeScript would generate. Usage import { convertToDecl

Mar 3, 2022

Screeps Typescript Starter is a starting point for a Screeps AI written in Typescript.

Screeps Typescript Starter Screeps Typescript Starter is a starting point for a Screeps AI written in Typescript. It provides everything you need to s

Jan 27, 2022

Movehat is a TypeScript SDK for Move on Sui built on top of Sui's TypeScript SDK and our fork of Ian Macalinao's `move-ts`.

Movehat Movehat is a TypeScript SDK for Move on Sui built on top of Sui's TypeScript SDK and our fork of Ian Macalinao's move-ts. Movehat aspires to b

Sep 30, 2022

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

🐬 HypeScript Introduction This is a simplified implementation of TypeScript's type system that's written in TypeScript's type annotations. This means

Dec 20, 2022

A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and configure Typescript on it.

CTSP- Create TS Project A CLI tool to create a NodeJS project with TypeScript CTSP is a CLI tool to make easier to start a new NodeJS project and conf

Sep 13, 2022

This project is a boilerplate for Next and TypeScript projects. This template was built with Vite, TypeScript and Stitches.

This project is a boilerplate for Next and TypeScript projects. This template was built with Vite, TypeScript and Stitches.

Awesome Template Stitches — NextJS, TypeScript, Stitches and Design Tokens Summary About this template Avaliale scripts Other scripts available Main t

Dec 29, 2022

TypeScript CLI for creating HTML & CSS & TypeScript project with different bundlers, v2022.10.23 is ready on NPM

TypeScript CLI for creating HTML & CSS & TypeScript project with different bundlers, v2022.10.23 is ready on NPM

TSCI CLI TypeScript CLI for creating HTML & CSS & TypeScript project with different bundlers. Installation npm i -g tsci Usage Want to contribute? You

Dec 14, 2022

A new Node.js resource built using Gatsby.js with React.js, TypeScript, and Remark.

Nodejs.dev Nodejs.dev site built using Gatsby.js with React.js, TypeScript, SCSS, and Remark. You can find the latest Figma design protype here. 🚀 Ge

Jan 5, 2023
Releases(1.0.1)
  • 1.0.1(Oct 15, 2022)

    What's Changed

    • rename functions to be consistent with Javascript by @xeinebiu in https://github.com/xeinebiu/ts-iterable/pull/1

    New Contributors

    • @xeinebiu made their first contribution in https://github.com/xeinebiu/ts-iterable/pull/1

    Full Changelog: https://github.com/xeinebiu/ts-iterable/commits/1.0.1

    Source code(tar.gz)
    Source code(zip)
Owner
null
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A small (~600B gzip), useful set of methods for lazy iteration of iterables.

@ricokahler/lazy · A small (~600B gzip*), useful set of methods for lazy iteration of iterables. Why this lazy lib? Do I even need a lazy lib? Install

Rico Kahler 11 Sep 10, 2022
Well-tested utility functions dealing with async iterables

aitertools This library provides a well-tested collection of small utility functions dealing with async iterables. You can think of it as LINQ or aite

Hong Minhee (洪 民憙) 11 Aug 15, 2022
Trusted timestamps that you can physically include in photos, videos and live streams using QR codes and audible data signals.

QR Date This is the reference implementation for the first version of QR Date, a signed timestamp inside a QR code that you can use to verify the date

QR Date 36 Oct 5, 2022
`morphdom` integration for Turbo Streams

Turbo Morph turbo-morph is a morphdom integration for Turbo Streams. It provides a new Turbo Stream morph action. Note: Requires Turbo 7.2+ Getting St

Marco Roth 48 Dec 29, 2022
WIP: Power-pack for Turbo Streams

TurboPower turbo_power is a power-pack for Turbo Streams. It provides Turbo Streams with a bunch of new actions and additionally adds the morph action

Marco Roth 123 Jan 4, 2023
:books: The definitive guide to TypeScript and possibly the best TypeScript book :book:. Free and Open Source 🌹

TypeScript Deep Dive I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack

Basarat Ali Syed 18.7k Jan 4, 2023
Variant types in Roblox TypeScript - Ported from Vanilla TypeScript

Variant (for Roblox) This is a roblox typescript variant (heh, pun) of Variant. See the Variant documentation on how to use Variant. A variant type is

Australis 2 Jun 3, 2022
A Lua plugin, written in TypeScript, to write TypeScript (Lua optional).

typescript.nvim A minimal typescript-language-server integration plugin to set up the language server via nvim-lspconfig and add commands for convenie

Jose Alvarez 315 Dec 29, 2022