Last active
August 31, 2015 22:19
-
-
Save Silverwolf90/52575451d8a6769cd495 to your computer and use it in GitHub Desktop.
Simplistic pattern matching in less than 25 lines using switch statement
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
'use strict'; | |
const types = { | |
[Number ] : 'number', | |
[String ] : 'string', | |
[Boolean] : 'boolean', | |
[Object ] : 'object' | |
}; | |
function of(...typesToCheck) { | |
let typeNames = Object.keys(types).map(key => types[key]); | |
let patternMatchingString = typesToCheck | |
.map((type) => typeof type === 'function' ? types[type] : type ) | |
.map((typeName) => typeNames.indexOf(typeName)) | |
.join(' '); | |
return patternMatchingString; | |
} | |
function match(...args) { | |
return of(...args.map(arg => typeof arg)); | |
} | |
// Example: | |
function doStuff(a, b) { | |
switch(match(a, b)) { | |
case of(Number, Number ) : return true; | |
case of(String, String ) : return 'strings'; | |
case of(String, Boolean) : return 'stringbool'; | |
case of(Object, Object ) : return 'objects'; | |
default : return false; | |
} | |
} | |
console.log(doStuff(2, 2)); //=> true | |
console.log(doStuff('a', 'b')); //=> 'strings' | |
console.log(doStuff('s', true)); //=> 'stringbool' | |
console.log(doStuff({}, [])); //=> 'objects' | |
console.log(doStuff('asdf')); //=> false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment