Created
December 15, 2016 09:00
-
-
Save gmmorris/eff1a735c6d1d35dd076dcd81ab21b14 to your computer and use it in GitHub Desktop.
Build a set of if-elseif-else switches using functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const conditional = () => { | |
let elseThen = i => i; | |
const conditions = []; | |
function cond (val) { | |
const res = conditions | |
.find(condPair => condPair.test(val)); | |
return res | |
? res.then(val) | |
: elseThen(val); | |
} | |
cond.ifThen = (test, then) => { | |
conditions.push({ test, then }); | |
return cond; | |
} | |
cond.elseThen = (then) => { | |
elseThen = then; | |
return cond; | |
} | |
return cond; | |
} | |
const myTest = conditional() | |
.ifThen(val => val % 2 === 1, val => `${val} is odd`) | |
.ifThen(val => val % 2 === 0, val => `${val} is even`) | |
.ifThen(val => isNaN(val), val => `${val} is not a number`) | |
.elseThen(val => `${val} is completly unknown to me`); | |
console.log(myTest(1)); | |
console.log(myTest(2)); | |
console.log(myTest(55)); | |
console.log(myTest(16554)); | |
console.log(myTest('123s')); | |
console.log(myTest(1/0)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment