Flexible whitelist/blacklist testing
Synopsis
var GreyList = ;var greylist = options;var passed = greylist;
Options
The options object may itself be undefined. When it is defined, there are two options:
options.white
A whitelist. Only listed strings can pass. If undefined
, all strings are included. If an empty array, all strings are excluded.
options.black
A blacklist. Listed strings are blocked. If undefined
or an empty array, all strings are included.
Whitelist and blacklist values
May be any of:
- an array — elements that are not already strings or
RegExp
objects are converted to strings - a
RegExp
— converted to a single-element array - a string — converted to a single-element array
- an object — converted to array comprised of the keys of the object's enumerable members that have defined values
undefined
— a no-op
Methods
test
The single defined method, test(string)
, returns a boolean subject to the following conditions:
- If
whitelist
is defined, the test string mustmatch
one of its elements. - If
blacklist
is defined, the test string must not match any of its elements.
This method is a suitable argument to Array.prototype.filter
so long as it's properly bound:
var words = ...; // provide a list of words to excludevar greylist = options; // The following three lines are equivalent:var acceptableWords = words;var acceptableWords = words;var byGreylist = greylisttest acceptableWords = words;
Examples
var greylist = 'abc''de''f';greylist // true: whitelisted and no blacklistgreylist // false: not in whitelistgreylist // true: whitelisted and no blacklistgreylist // true: whitelisted and no blacklistgreylist // false: not in whitelist var threeOrMore = /^[a-z]{3,}$/;var greylist = undefined threeOrMore 'f';greylist // false: no whitelist but strings of length 3 or more are blacklistedgreylist // true: no whitelist and not blacklistedgreylist // true: no whitelist and not blacklistedgreylist // false: no whitelist but blacklistedgreylist // true: no whitelist and not blacklisted var greylist = 'abc''de''f' threeOrMore 'f';greylist // false: whitelisted but strings of length 3 or more are blacklistedgreylist // false: not in whitelistgreylist // true: whitelisted and not blacklistedgreylist // false: whitelisted but blacklistedgreylist // false: not in whitelist