1.0.0 • Published 3 years ago
@vsadx/overloads v1.0.0
Overloads for JS
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.
<br>
# Getting Started
## How to write an overload
<br>
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:
```js
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
})
// runs the Boolean
version
switchInput(myInputElementB, true)
<br>
# Extras
## Using overloads for better optional parameters
<br>
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:
```js
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
})
functionName.if(Number, num => console.log(Num: #${num}
))
functionName.if(String, str => console.log(Text: "${num}"
))
Here's a shorter way:
```js
const functionName = overload()
.if(Number, num => console.log(`Num: #${num}`))
.if(String, str => console.log(`Text: "${str}"`))
1.0.0
3 years ago