Skip to content
HussseinkizzPublic

About

Functional Programming Library For Typescript

Topics

Resources

Stars

8 stars

Watchers

0 watching

Forks

Repository files navigation

slang-ts

npm version license

An opinionated functional programming library for TypeScript.

A collection of utilities and mechanisms brought over from languages like Rust and Erlang. Each utility is deliberately selected and built from scratch with zero dependencies.

Install

npm i slang-ts

Why I Made This?

Well I love functional programming so much and hate classes and inheritance with all my heart, sorry no offense intended, I prefer composition and functions over those but well that's not exactly why I made this despite part of the reasons, main reason was all functional programming (FP) libraries in typescript and javascript were really complicated, think effect ts and rameda, all seemed like needed one to be so nerdy, so was like I need something simple I can work with comfortably and can onboard a team to over an evenning, one by one, got each utility crafted out, to what you see today, here I aimed more for practicality than correctness, so yes some functions are not pure, a few rules broken, a few opinions, and all that makes this fun to use, try it!

Quick start

So let's say your function can fail. Instead of throwing, you return a Result: Ok with the value or Err with a message, and the caller checks isOk before reading either:

import { Ok, Err, type Result, println } from "slang-ts";

function splitBill(total: number, people: number): Result<number, string> {
  if (people === 0) {
    return Err("Add at least one person to split the bill");
  }

  return Ok(total / people);
}

const share = splitBill(120, 4);

if (share.isOk) {
  println("Each person pays:", share.value); // 30
} else {
  println("Could not split the bill:", share.error);
}

println is optional: it's a small development logger, silent in production.

Imports

Import only what you use:

import { option, Ok, Err, atom, match } from "slang-ts";

Choose by what you want to solve

If you need… Use
A value which may be missing Option
An operation which can fail Result and SafeTry
Several results checked together combineResults and combineErrors
Pattern matching over results Match
Steps which stop at the first failure Pipe
Timeout, retry, or cancellation SuperPromise
Ordered, parallel, or race tasks SuperRunner
A shared concurrency limit taskGroup
Strict array bounds or paging list
Nested record reads with defaults struct
Set membership and set operations sets
Lazy pipelines over an Ok Ok.iterate
Cached function calls memoized
Step history or undo createStepper
Events between parts of an app Channel
A lifecycle trigger which fires once Signal

What's inside

Error handling and flow

Composition and conversion

  • Atom (atom)
  • To (.to() on every wrapper, and _to)
  • Zip (zip, zipWith, unzip)

Collections and data

Async and lifecycle

Small utilities

  • println (println, setEnvironment)

Full reference: docs index. Feature list: CHANGELOG.md. Agent guide: skill/SKILL.md.

Real-world examples

Load a value which can fail: SafeTry + Result

Loading saved settings can fail two ways: the saved text is not valid JSON, or the role inside is one you do not support. safeTry turns both into one Result:

import { Ok, Err, safeTry, type Result, println } from "slang-ts";

type Role = "admin" | "member";

type SavedSettings = {
  role: string;
};

function parseRole(value: string): Result<Role, string> {
  if (value === "admin" || value === "member") {
    return Ok(value);
  }

  return Err("Unknown role");
}

const savedText = '{"role":"admin"}';

const role = safeTry(() => {
  const settings = JSON.parse(savedText) as SavedSettings;

  return parseRole(settings.role);
});

if (role.isOk) {
  println("Role:", role.value); // "admin"
} else {
  println("Could not load the role:", role.error);
}

A throw from JSON.parse and an Err from parseRole both come back as Err, so you check the result once. safeTry itself never throws. Your function is sync here, so the Result comes back directly; an async function gives you a promise of it to await.

Full detail: SafeTry and Result.

Call an API with a timeout and retries: SuperPromise

Your function receives an AbortSignal to pass along to fetch. timeout stops an attempt once it takes too long, retry runs it again after a failure, and the call resolves to Ok or Err. It never rejects:

import { superPromise, println } from "slang-ts";

type User = {
  id: string;
  name: string;
};

const user = await superPromise(
  async (signal: AbortSignal): Promise<User> => {
    const response = await fetch("https://example.com/api/users/u_1", { signal });

    if (!response.ok) {
      throw new Error("Could not load the user");
    }

    return (await response.json()) as User;
  },
  { timeout: 5000, retry: 2 }, // 5 seconds per attempt, up to 2 retries
);

if (user.isOk) {
  println("User:", user.value.name); // "Ada"
} else {
  println("Could not load the user:", user.error);
}

Full detail: SuperPromise.

Page a list and shape records: list + struct

list keeps bounds strict: a range outside the array fails instead of returning fewer items. struct reads and shapes records, keeping only the fields you choose.

import { list, struct, println } from "slang-ts";

type User = {
  id: string;
  name: string;
  avatar?: string;
  email: string;
};

const users: User[] = [
  { id: "u_1", name: "Ada", avatar: "/avatars/ada.png", email: "ada@example.com" },
  { id: "u_2", name: "Grace", email: "grace@example.com" },
  { id: "u_3", name: "Linus", email: "linus@example.com" },
];

const page = 1;
const size = 2;

const total = list(users).count().else(0);
const start = Math.min(page * size, total);
const end = Math.min(start + size, total);

const paged = list(users).range(start, end).else([]);

const cards = paged.map((user) => struct(user).pick("id", "name", "avatar").else(user));

println(cards); // [{"id":"u_3","name":"Linus"}]

list never shortens a range, so the example clamps the window and lets the last page be short. struct then keeps only the fields the card needs.

Full detail: list and struct.

Development

Install with Bun, then run the full check:

bun install
bun run export

export runs the tests, checks types, and builds minified ESM with bundled declarations into dist/. npm publish runs it through prepublishOnly, so you never ship stale output. Tests live in tests.

Building needs Node.js ^22.18.0 || ^24.11.0 || >=26.0.0. That's for the build tool, not for projects using Slang.

Contributing

Got a utility from another language which belongs here? Open an issue or a pull request. Contributions are welcome.

Requirements

  • ESM only. You'll use import; require isn't supported.
  • Node.js 20+ or a modern browser.
  • TypeScript 5.9.x or 7.0.x if you want the bundled types. Plain JavaScript works too.
  • Zero runtime dependencies.

License

MIT License. See LICENSE.

About

Functional Programming Library For Typescript

Topics

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages