New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

defmethod

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

defmethod

Multimethods for TypeScript

latest
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

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);

FAQs

Package last updated on 03 Jun 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts