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

tiny-multimethods

v0.0.3

Published

Tiny port of Clojure's multimethods with zero dependencies and 30 LOC.

Downloads

165

Readme

tiny-multimethods

A lightweight implementation of Clojure-style multimethods for JavaScript in under 30 lines of code. Define functions that dispatch to different implementations based on runtime values.

Installation

npm install tiny-multimethods

Usage

import { defmulti, DEFAULT } from 'tiny-multimethods';

// Create a multimethod that dispatches based on shape type
const calculateArea = defmulti(
  shape => shape.type,
  ['circle', shape => Math.PI * shape.radius ** 2],
  ['rectangle', shape => shape.width * shape.height],
  [DEFAULT, shape => {
    throw new Error(`Can't calculate area of ${shape.type}`);
  }]
);

// Use it
console.log(calculateArea({ type: 'circle', radius: 5 })); // 78.54...
console.log(calculateArea({ type: 'rectangle', width: 4, height: 3 })); // 12

// Add new methods dynamically
calculateArea.addMethod('triangle', shape =>
  (shape.base * shape.height) / 2
);

Features

  • 🪶 Lightweight: Less than 30 lines of code
  • 🎯 Flexible dispatch: Use any function to determine which method to call
  • 🔌 Extensible: Add new methods at runtime
  • 🛟 Default cases: Handle unknown values gracefully

API

defmulti(dispatchFn, ...methods)

Creates a new multimethod using the provided dispatch function and method implementations.

Parameters:

  • dispatchFn: Function that takes an argument and returns a dispatch value
  • ...methods: Array of [dispatchValue, implementation] pairs

Returns: A function that will dispatch to the appropriate method based on the dispatch function's result.

DEFAULT

A special symbol used to define default method implementations.

Examples

Content Renderer

const renderContent = defmulti(
  content => content.type,
  ['text', content => `<p>${content.value}</p>`],
  ['image', content => `<img src="${content.url}" alt="${content.alt || ''}">`],
  ['video', content => `
    <video controls>
      <source src="${content.url}" type="video/mp4">
    </video>
  `],
  [DEFAULT, content => `<div>Unsupported content type: ${content.type}</div>`]
);

// Usage
renderContent({ type: 'text', value: 'Hello World' });
// <p>Hello World</p>

Priority-based Notifications

const notifyUser = defmulti(
  notification => notification.priority,
  ['high', n => {
    console.log('🚨 URGENT:', n.message);
    return 'high-priority-handled';
  }],
  ['medium', n => {
    console.log('ℹ️ NOTICE:', n.message);
    return 'medium-priority-handled';
  }],
  ['low', n => {
    console.log('📝 FYI:', n.message);
    return 'low-priority-handled';
  }]
);

notifyUser({ priority: 'high', message: 'System is down!' });
// 🚨 URGENT: System is down!

Complex Dispatch

const calculateShipping = defmulti(
  // Dispatch based on multiple factors
  order => `${order.method}-${order.type}`,

  ['express-fragile', order => {
    const baseCost = order.weight * 0.1 + order.distance * 0.05;
    return baseCost * 2.5 + 15; // Extra handling + insurance
  }],

  ['standard-regular', order => {
    return order.weight * 0.1 + order.distance * 0.05;
  }]
);

Dynamic Method Addition

const processor = defmulti(
  data => data.version,
  ['v1', data => ({ ...data, upgraded: true })]
);

// Add support for new version later
processor.addMethod('v2', data => ({
  ...data,
  upgraded: true,
  timestamp: Date.now()
}));

Why Use This?

  • Clean Code Organization: Group related implementations together instead of scattered if/else statements
  • Runtime Extensibility: Add new behaviors without modifying existing code
  • Simple but Powerful: Lightweight implementation that handles most common use cases
  • Flexible Dispatch: Use any function to determine which implementation to use

Inspiration

This implementation is inspired by Clojure's multimethod system, bringing similar capabilities to JavaScript in a lightweight package.

License

MIT

Contributing

Issues and pull requests are welcome! Feel free to contribute to make this tiny utility even better.