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

defmethod

v1.0.1

Published

Multimethods for TypeScript

Downloads

3

Readme

defmethod

A light weight library for Multimethods / Multiple Dispatch in TypeScript.

Installation

bun add defmethod

Usage

import { defmulti, defmethod } from "defmethod";

enum Type {
  Foo,
  Bar,
  Baz,
}

interface Params {
  type: Type;
  message: string;
}

// create a multimethod
const myfn = defmulti<
  Params, // type of myfn's argument
  string, // type of myfn's handlers' return values
  Type, // type of the dispatch fn's return value
>(
  (x) => x.type // dispatch fn
);

// register handlers for the multimethod
defmethod(
  myfn, // multimethod
  Type.Foo, // dispatch val
  (x) => `foo ${x.message}` // dispatch handler
);
defmethod(myfn, Type.Bar, (x) => `bar ${x.message}`);
defmethod(myfn, Type.Baz, (x) => `baz ${x.message}`);

// call the multimethod
myfn({ type: Type.Foo, message: " hello" }) // => "foo hello"
myfn({ type: Type.Bar, message: " world" }) // => "bar world"
myfn({ type: Type.Baz, message: "!" }) // => "baz!"

// type variables are optional
const otherfn = defmulti((x) => x.type);

defmethod(otherfn, Type.Foo, (x) => `otherfoo ${x.message}`);
// etc.

Examples

Discriminating unions

A common pattern in large-ish TypeScript code bases is that of discriminating unions. Whenever one wants to do something non-generic with objects of this type one needs to check the type of the object and switch over its type. Multimethods provides a flexible alternative to large switch blocks.

type NetworkLoadingState = {
  state: "loading";
};

type NetworkFailedState = {
  state: "failed";
  code: number;
};

type NetworkSuccessState = {
  state: "success";
  response: {
    title: string;
    duration: number;
    summary: string;
  };
};

type NetworkState =
  | NetworkLoadingState
  | NetworkFailedState
  | NetworkSuccessState;

// switch case
const handle = (ns: NetworkState) => {
  switch(ns.type) {
    case "loading":
      ...
    case "failed":
      ...
    case: "success":
      ...
  }
}

// multimethods
const handle = defmethod((ns) => ns.type);

defmethod(handle, "loading", (ns) => ...);
defmethod(handle, "failed", (ns) => ...);
defmethod(handle, "success", (ns) => ...);

Collatz sequences

The multimethod and dispatch fn can take any argument and return any value, it does not necessarily need to be an object. One can for example use multimethods to generate Collatz sequences.

const collatzStep = defmulti((n: number) => n % 2 === 0 ? "even" : "odd");

defmethod(collatzStep, "even", (n: number) => n / 2);
defmethod(collatzStep, "odd", (n: number) => 3 * n + 1);

// This fn might not terminate - but it probably will
const collatzSeq = (n: number) => {
  if (n <= 0) {
    throw new Error("n must be positive");
  }

  const steps = [n];

  while (n !== 1) {
    n = collatzStep(n);
    steps.push(n);
  }

  return steps;
};

collatzSeq(27); // => [27, 82, 41, 124, 62, 31, ...]

React

Works well with React too.

import { defmulti, defmethod } from "multimethods"

import { BarChart } from "./PieChart"
import { LineChart } from "./PieChart"
import { PieChart } from "./PieChart"

enum ChartType {
  Bar,
  Line,
  Pie,
}

interface Props {
  type: ChartType,
  title: string;
  data: object,
}

export const Chart = defmulti<Props, JSX.Element, ChartType>(({ type }) => type);

defmethod(Chart, ChartType.Bar, (props) => {
  return <BarChart {...props} />;
});

defmethod(Chart, ChartType.Row, ({ data, title }) => {
  return <LineChart {...props} />;
});

defmethod(Chart, ChartType.Pie, ({ data, title }) => {
  return <PieChart {...props} />;
});

One could also register methods within each component's file.

// Chart.tsx
import { defmulti } from "multimethods"

enum ChartType {
  Bar,
  Line,
  Pie,
}

interface Props {
  type: ChartType,
  title: string;
  data: object,
}

export const Chart = defmulti<Props, JSX.Element, ChartType>(({ type }) => type);

// BarChart.tsx
import { defmethod } from "multimethods"
import { Chart, Props, ChartType } from "./Chart"

const BarChart = (p: Props) => {
  return <>...</>
};

defmethod(Chart, ChartType.Bar, BarChart);

// LineChart.tsx
import { defmethod } from "multimethods"
import { Chart, Props, ChartType } from "./Chart"

const LineChart = (p: Props) => {
  return <>...</>
};

defmethod(Chart, ChartType.Line, LineChart);

// PieChart.tsx
import { defmethod } from "multimethods"
import { Chart, Props, ChartType } from "./Chart"

const PieChart = (p: Props) => {
  return <>...</>
};

defmethod(Chart, ChartType.Pie, PieChart);