Skip to content

Instantly share code, notes, and snippets.

@Dakedres
Created August 24, 2018 00:24
Show Gist options
  • Save Dakedres/88f65b084b732a0af2ae4921d44a78cc to your computer and use it in GitHub Desktop.
Save Dakedres/88f65b084b732a0af2ae4921d44a78cc to your computer and use it in GitHub Desktop.
/**
* Represents a pattern
* @constructor
* @param {string | class} type The desired class of the object, or a string representing the type.
* @param {func} func Function for testing if the object matches the desired pattern or not, must take a value and return either a boolean or array of booleans.
* @param {error} error Error to be thrown when .throw() is used, if none is provided.
*/
class Pattern {
constructor(type, func, error) {
const isString = typeof type === 'string';
if( !(type instanceof Function || isString) ) throw new TypeError('Type must be either a class or string representing its type.');
if(typeof func !== 'function') throw new TypeError('Func must be a function.');
if( !(error instanceof Error) && error != null ) throw new TypeError('Error must be an instance of an error.');
this.type = isString ? type.toLowerCase() : type;
this.func = func;
this.error = error || new TypeError('No match.');
}
/**
* Test if a value matches the pattern.
* @param {*} value The value to test.
* @returns {Boolean}
*/
test(value) {
if( !(typeof this.type === 'string' ? typeof value === this.type.toLowerCase() : value instanceof this.type) ) return new PatternMatchResults(false, this.error);
const tests = this.func(value);
if(!Array.isArray(tests)) return new PatternMatchResults(tests == true, this.error);
for(let i = 0; i < tests.length; i++) {
if(!tests[i]) return new PatternMatchResults(false, this.error);
}
return new PatternMatchResults(true);
}
}
class PatternMatchResults extends Boolean {
constructor(value, error) {
super(value);
this.error = error;
}
/**
* If the match fails, throw the error specified in the creation of the pattern, or throw a new error.
* @param {Error} [err] Error to throw instead of the one specified in the creation of the pattern.
* @returns {Boolean}
*/
throw(err) {
if(!super.valueOf()) throw this.error; else return true;
}
}
module.exports = Pattern;
@RuyiLi
Copy link

RuyiLi commented Aug 24, 2018

despacito

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment