Skip to content

Instantly share code, notes, and snippets.

@Silverwolf90
Last active August 31, 2015 22:19
Show Gist options
  • Save Silverwolf90/52575451d8a6769cd495 to your computer and use it in GitHub Desktop.
Save Silverwolf90/52575451d8a6769cd495 to your computer and use it in GitHub Desktop.
Simplistic pattern matching in less than 25 lines using switch statement
'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