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

@vsadx/overloads

v1.0.0

Published

Create typed overloads for functions

Downloads

12

Readme

Overloads for JS

What are overloads for?

Overloads come from other languages where the type of a variable is more obvious. Using overloads, you can write less code, yet understand its intent faster. How does it work? Overloads replace if (), else, or switch statements - if you're looking at a variable's type. We do this in JavaScript!

Notice the if, else if pair in this code sample, look at how we use the typeof keyword in JavaScript to do "type checking":

function makeInput(startingValue) {

    const element = document.createElement("input")
    
    if(typeof startingValue === "number") {
        element.type = "number"        
        element.value = startingValue
    }
    else if(typeof startingValue === "boolean") {
        element.type = "checkbox"
        element.checked = startingValue
    }
    else {
        element.placeholder = startingValue
    }
    
    return element
}

Since JavaScript doesn't have overloads built in, we have write the type checking code ourself. Type checking in JS gets more complicated because typeof doesn't work well on things like HTMLElements for example. You might have to use instanceof in some places or do prototype matching.

Getting Started

How to write an overload

Overloads are easy! If you've ever written callback functions to addEventListener, or setTimeout you've already got the basics. Here's the first line of our overload:

import { overload } from "./overloads.js"

const switchInput = overload()

What's this? Each time you run overload() you get a new empty function you define later. Let's add our cases:

switchInput.if(HTMLInputElement, String, (element, startingValue) => {
    element.placeholder = startingValue
})

It's that easy, we can add the next case like this:

switchInput.if(HTMLInputElement, Number, (element, startingValue) => {
    element.type = "number"
    element.value = startingValue
})
switchInput.if(HTMLInputElement, Boolean, (element, startingValue) => {
    element.type = "checkbox"
    element.checked = startingValue
})

How to run the overloaded function

Just like in other languages, these overloads are ran exactly like any other function.

// runs the `String` version
switchInput(myInputElementA, "First Name")

// runs the `Boolean` version
switchInput(myInputElementB, true)

Extras

Using overloads for better optional parameters

In JavaScript, we use optional parameters all the time! We might have different code run depending on how many parameters are passed to our function. Overloads work here too, here's how:

const makeFormQuestion = overload()

makeFormQuestion.if(String, (question) => {
    const input = document.createElement("input")
    input.placeholder = question
    return input
})
makeFormQuestion.if(String, Array, (question, choices) => {
    const select = document.createElement("select")
    select.append(...choices)
    return select
})

How it works

You might want to take an extra look at these examples above if you get stuck, overloads work for primitives like Number, String, Boolean - or elements like HTMLElement, HTMLDivElement - or Array - even your custom JS classes. Overloads don't use a magic list of types it uses real type checking just like what you would ordinarily write. Also, it's not locked at two parameters, you overloadable functions can have as many parameters as you want.

This library has some TypeScript support; in our example, each variety of (element, startingValue) => would know that element was an HTMLInputElement. What about startingValue, it needs to have a different type depending on the case? It is also has its type automatically declared for you.

Defining overloads using the compact method

So far, we've been writing overloads like this:

const functionName = overload()

functionName.if(Number, num => console.log(`Num: #${num}`))
functionName.if(String, str => console.log(`Text: "${num}"`))

Here's a shorter way:

const functionName = overload()
    .if(Number, num => console.log(`Num: #${num}`))
    .if(String, str => console.log(`Text: "${str}"`))

Preventing more cases from being accidentally added later .lock

const toHtml = overload()
    .if(Array, list => `<ul> </ul>`)
    .if(String, text => `<p> </p>`)
    .lock()
    // no more `.if` functions can be added.

Catch all cases .else

const multiNumber = overload()
    .if(Number, Number, (a, b) => a * b)
    .if(Number, Number, Number, (a, b, c) => a * b / c)
    .else((...args) => console.error("None of your parameters matched any of the cases:", args))
    // `.else` always matches if no other cases were a match.