Coder Social home page Coder Social logo

vsadx / overloads-for-js Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 17 KB

Adds type-based overloads for functions.

Home Page: https://www.npmjs.com/package/@vsadx/overloads

JavaScript 100.00%
overloading-in-javascript typed-parameters optional-parameters overloaded-functions

overloads-for-js's Introduction

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.

overloads-for-js's People

Contributors

vsadx avatar

Stargazers

 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.