Published
Edited
Apr 12, 2021
Insert cell
Insert cell
Insert cell
function faultySwitchCaseExample (a) {
switch (a) {
case (Number.isNaN(a) === true):
return "it's not a number at all!";
case (< 10):
return "it's less than 10";
default:
return "it's greater than or equal to 10";
}
}
Insert cell
Insert cell
function ifElseIfExample (a) {
if (Number.isNaN(Number(a))) {
return "it's not a number at all"
} else if (a < 10) {
return "it's less than 10"
} else {
return "it's greater than on equal to 10"
}
}
Insert cell
Insert cell
isNan = (a) => Number.isNaN(Number(a))
Insert cell
Insert cell
"it's not a number at all"
Insert cell
Insert cell
[isNaN, () => "it's not a number at all"]
Insert cell
Insert cell
lt10 = (a) => a < 10
Insert cell
finalElse = (a) => a >= 10
Insert cell
Insert cell
myPatterns = [
[isNan, () => "it's not a number at all"],
[lt10, () => "it's less than 10"],
[finalElse, () => "it's greater than or equal to 10"]
]
Insert cell
Insert cell
function patternMatcher (patterns) {
return (input) => {
const head = patterns[0] // take the first pattern. the pattern is [condition, evaluator] or undefined
if (!head) throw new Error('No base case given') // if no pattern is found or given, throw error
const condition = head[0]
const evaluator = head[1]
if (condition(input)) {
return evaluator()
} else {
return patternMatcher(patterns.slice(1))(input)
}
}
}
Insert cell
Insert cell
whatIsA = patternMatcher(myPatterns)
Insert cell
whatIsA('something')
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more