-
Predicates
- all
- and
- any
- arr
- array
- arrayLike
- arrayOf
- arrLike
- arrOf
- asyncFn
- asyncFunction
- blank
- bool
- boolean
- date
- defined
- divBy
- divByWithRemainder
- divisible
- divisibleBy
- divisibleByWithRemainder
- divisibleWithRemainder
- empty
- emptyArr
- emptyArray
- endsWith
- eq
- equal
- equalTo
- false
- falsey
- falsy
- finite
- fn
- func
- function
- generator
- greater
- greaterEq
- greaterOrEqual
- greaterThan
- greaterThanOrEqual
- gt
- gtEq
- has
- hasOwn
- hasOwnProperty
- hasProperty
- in
- instance
- instanceOf
- int
- integer
- less
- lessEq
- lessOrEqual
- lessThan
- lessThanOrEqual
- lt
- ltEq
- map
- match
- matches
- nan
- NaN
- negate
- negative
- not
- notANumber
- notBlank
- notEmptyArr
- notEmptyArray
- null
- num
- number
- obj
- object
- objectOf
- objOf
- oneOf
- or
- plainObject
- positive
- primitive
- promiseLike
- prop
- property
- regexp
- regExp
- set
- startsWith
- str
- strictEqual
- strictEqualTo
- string
- struct
- structure
- symbol
- thenable
- true
- truthy
- undefined
- undefinedOr
- weakMap
- weakSet
-
Helpers
-
Common types
Returns a function that calls predicates and returns true if all of them are satisfied, otherwise returns false
const isBetween10And100 = is.all(is.greaterThan(10), is.lessThan(100));
isBetween10And100(0); // false
isBetween10And100(11); // true
Signature
is.all(...predicates: (Predicate | Function)[]) => Predicate<any>
Throws:
- TypeError - if not every predicate is a function
Returns a function that calls predicates in the order until one of them will be satisfied, otherwise returns false.
const isStringOrNumber = is.any(is.string, is.number);
isStringOrNumber(0); // true
isStringOrNumber('string'); // true
isStringOrNumber(undefined); // false
Signature
is.any(...predicates: (Predicate | Function)[]) => Predicate<any>
Throws:
- TypeError - if not every predicate is a function
Checks whether a value is an array
is.array([]); // true
is.array({}); // false
is.array('string'); // false
Signature
is.array<T = any>(value: any) => value is T[]
Checks whether value is async function. Only functions created with modifier "async" are considered async. Regular function that returns promise or accepts callback is not an async function.
More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction
is.asyncFunction(async () => {}); // true
is.asyncFunction(function* () {}); // false
is.asyncFunction(function() {}); // false
Signature
is.asyncFunction<T = any>(value: any) => boolean
Checks whether a value looks like an array That means:
- is an object
- has 'length' property
- 'length' property is a number greater or equal 0
is.arrayLike(arguments); // true
is.arrayLike(document.querySelectorAll('div')); // true
is.arrayLike([1, 2, 3]); // true
is.arrayLike({}); // false
Signature
is.arrayLike(value: any) => boolean
Checks whether every element of an array passes the predicate
const isArrayOfStrings = is.arrayOf(is.string);
isArrayOfStrings(['1', '2']); // true
// same as
is.arrayOf(is.string, ['1', '2']); // true
// same as
is.arrayOf(String, ['1', '2']); // true
isArrayOfStrings([1, 2]); // false
Signature
is.arrayOf<T = any>(predicate: Predicate | Function) => TypeGuardPredicate<T[]>
is.arrayOf<T = any>(predicate: Predicate | Function, value: any[]) => boolean
is.arrayOf<T>(predicate: Predicate | Function, value?: any[], ...extraArgs: any[]) => boolean | TypeGuardPredicate<T[]>
Throws:
- TypeError - if predicate is not a function
Checks whether a value is empty string or contains only whitespaces
is.blank(''); // true
is.blank(' '); // true
is.blank('test'); // false
Signature
is.blank(value: any) => boolean
Checks whether a value is a boolean
is.boolean(true); // true
is.boolean(false); // true
is.boolean(0); // false
Signature
is.boolean(value: any) => boolean
Checks whether a value is a Date object
is.date(new Date()); true
is.date(1415402574000); // false
Signature
is.date(value: any) => boolean
Checks whether a value is not undefined - in other words, is defined
is.defined(''); // true
is.defined(1); // true
is.defined(undefined); // false
Signature
is.defined(value: any) => boolean
Checks whether a value is a number and it's divisible by a divisor
is.divisible(7, 14); // true
is.divisible(7)(14); // true
is.divisible(7, 10); // false
Signature
is.divisible(divisor: number) => Predicate<number>
is.divisible(divisor: number, value: number) => boolean
is.divisible(divisor: number, value?: number) => boolean | Predicate<number>
Checks whether a value is a number and it's divisible by divisor with given remainder In other words value % div === remainder
is.divisibleWithRemainder(3, 2, 5); // true since 5%3 === 2
is.divisibleWithRemainder(3, 2)(5); // true
is.divisibleWithRemainder(3, 1, 5); // false since 5%3 !== 1
const isEven = is.divisibleWithRemainder(2, 1);
isEven(1); // true
isEven(2); // false
isEven(3); // true
Signature
is.divisibleWithRemainder(divisor: number, remainder: number) => Predicate<number>
is.divisibleWithRemainder(divisor: number, remainder: number, value: number) => boolean
is.divisibleWithRemainder(divisor: number, remainder: number, value?: number) => boolean | Predicate<number>
Throws:
- Error - if less than 2 arguments provided
- Error - if the divisor is 0
- Error - if the remainder is greater than the divisor
- TypeError - if the divisor is not a finite number
- TypeError - if the remainder is not a finite number
Checks whether a value is empty Value is empty when:
- is an array like object with length === 0
- is an object without enumerable properties
- is an empty string
- is undefined
is.empty(''); // true
is.empty([]); // true
is.empty({}); // true
is.empty(undefined); // true
is.empty([1]); // false
is.empty('test'); // false
Signature
is.empty(value: any) => boolean
Checks whether value is an empty array
is.emptyArray([]); // true
is.emptyArray([1]); // false
is.emptyArray(''); // false
Signature
is.emptyArray<T = any>(value: any) => boolean
Checks whether a string ends with a given suffix
const isYelling = is.endsWith('!');
isYelling('shut up!'); // true
// same as
is.endsWith('!', 'shut up!'); // true
isYelling('quiet please'); // false
Signature
is.endsWith(suffix: string) => Predicate<string>
is.endsWith(suffix: string, value: string) => boolean
is.endsWith(suffix: string, value?: string) => boolean | Predicate<string>
Throws:
- TypeError - if suffix is not a string
- Error - if suffix is empty
Checks whether values are equal (using == operator)
const isTimmy = is.equal('Timmy');
isTimmy('Timmy'); // true
// same as
is.equal('Timmy', 'Timmy'); // true
is.equal(1, '1'); // true
isTimmy('Franko'); // false
Signature
is.equal(expected: any) => Predicate<any>
is.equal(expected: any, value: any) => boolean
is.equal(expected: any, value?: any) => boolean | Predicate<any>
Checks whether a value is false a boolean false
is.false(false); // true
is.false(0); // false
Signature
is.false(value: boolean) => boolean
Checks whether a value is falsy
is.falsy(0); // true
is.falsy(false); // true
is.falsy(1); // false
Signature
is.falsy(value: any) => boolean
Checks whether a value is a number and it's finite
is.finite(1); // true
is.finite(Infinity); // false
Signature
is.finite(value: any) => boolean
Checks whether a value is a function
is.function(function() {}); // true
is.function(alert); // true
is.function('alert'); // false
Signature
is.function(value: any) => boolean
Checks whether a value is generator
is.generator(function* gen() {}); // true
is.generator(function(){})); // false
Signature
is.generator(value: any) => boolean
Checks whether a value is greater than expected number
const isGreaterThan0 = is.greaterThan(0);
isGreaterThan0(10); // true
// same as
is.greaterThan(0, 10); // true
isGreaterThan0(-1); // false
Signature
is.greaterThan<T = number>(expected: T) => Predicate<T>
is.greaterThan<T = number>(expected: T, value: any) => boolean
is.greaterThan<T = number>(expected: T, value?: any) => boolean | Predicate<T>
Checks whether a value is greater or equal to expected number
const isAdultAge = is.greaterThanOrEqual(18);
isAdultAge(22); // true
// same as
is.greaterThanOrEqual(18, 22);
isAdultAge(16); // false
Signature
is.greaterThanOrEqual<T = number>(expected: T) => Predicate<T>
is.greaterThanOrEqual<T = number>(expected: T, value: any) => boolean
is.greaterThanOrEqual<T = number>(expected: T, value?: any) => boolean | Predicate<T>
Checks whether an object has own property
const isCustomized = is.hasOwnProperty('delay');
const Timer = function() {};
Timer.prototype.delay = 100;
const timer1 = new Timer();
const timer2 = new Timer();
timer1.delay = 1000;
isCustomized(timer1) // true
// same as
is.hasOwnProperty('delay', timer1); // true
isCustomized(timer2); // false
Signature
is.hasOwnProperty(property: string | Symbol) => Predicate<any>
is.hasOwnProperty(property: string | Symbol, object: object) => boolean
is.hasOwnProperty(property: string | Symbol, object?: object) => boolean | Predicate<any>
Throws:
- TypeError - if property is not a string or a symbol
Checks whether an object has a given property
const isDuck = is.hasProperty('quack');
isDuck({quack: ':)'}); // true
// same as
is.hasProperty('quack', {quack: ':)'}); // true
isDuck({type: 'car'}); // false
Signature
is.hasProperty(property: string | Symbol) => Predicate<any>
is.hasProperty(property: string | Symbol, object: Object) => boolean
is.hasProperty(property: string | Symbol, object?: Object) => boolean | Predicate<any>
Throws:
- TypeError - if property is not a string
Checks whether a value exists in collection Values are compared using === operator
const isImage = is.in(['image/gif', 'image/jpeg']);
// same as
// const isImage = is.oneOf('image/gif', 'image/jpeg');
isImage('image/jpeg'); // true
// same as
is.in(['image/gif', 'image/jpeg'], 'image/jpeg'); // true
isImage('text/html'); // false
Signature
is.in(collection: any[]) => Predicate<any>
is.in(collection: any[], value: any) => boolean
is.in(collection: any[], value?: any) => boolean | Predicate<any>
Throws:
- TypeError - if collection is not an array
- Error - if collection is empty
Checks whether a value is an instance of given "class"
const Duck = function() {};
const Car = function() {};
const isDuck = is.instanceOf(Duck);
isDuck(new Duck); // true
// same as
is.instanceOf(Duck, new Duck); // true
isDuck(new Car); // false
Signature
is.instanceOf<T>(clazz: Function) => TypeGuardPredicate<T>
is.instanceOf<T>(clazz: Function, value: any) => boolean
is.instanceOf<T>(clazz: Function, value?: any) => boolean | TypeGuardPredicate<T>
Throws:
- TypeError - if class is not a function
Checks whether a value is an integer
is.integer(10); // true
is.integer(10.4); // false
Signature
is.integer(value: any) => boolean
Checks whether a value is less than expected number
const isChildAge = is.lessThan(18);
isChildAge(10); // true
// same as
is.lessThan(18, 10); // true
isChildAge(18); // false
Signature
is.lessThan<T = number>(expected: T) => Predicate<T>
is.lessThan<T = number>(expected: T, value: any) => boolean
is.lessThan<T = number>(expected: T, value?: any) => boolean | Predicate<T>
Checks whether a value is less or equal to expected number
const isChildAge = is.lessThanOrEqual(17);
isChildAge(10); // true
// same as
is.lessThanOrEqual(17, 10); // true
isChildAge(18); // false
Signature
is.lessThanOrEqual<T = number>(expected: T) => Predicate<T>
is.lessThanOrEqual<T = number>(expected: T, value: any) => boolean
is.lessThanOrEqual<T = number>(expected: T, value?: any) => boolean | Predicate<T>
Checks whether a value is a string and matches a regexp
const isWindows9x = is.matches(/^Windows 9/);
isWindows9x('Windows 9'); // true - :D
// same as
is.matches(/^Windows 9/, 'Windows 9'); // also true - hue hue
isWindows9x('Windows 10'); // false
Signature
is.matches(regexp: RegExp) => Predicate<string>
is.matches(regexp: RegExp, value: string) => boolean
is.matches(regexp: RegExp, value?: string) => boolean | Predicate<string>
Throws:
- TypeError - if regexp is not a regexp
Check whether value is an instance of Map
Signature
is.map<K = any, V = any>(value: any) => boolean
Checks whether a value is a NaN number
is.NaN(NaN); // true
is.NaN(10); // false
Signature
is.notANumber(value: any) => boolean
Checks whether a value is a negative number
is.negative(-1); // true
is.negative(0); // false
Signature
is.negative(value: any) => boolean
Negates result of a predicate
const isNotEmpty = is.not(is.empty);
isNotEmpty([1, 2]);// true
// same as
is.not(is.empty, [1, 2]); // true
isNotEmpty(''); // false
Signature
is.negate(predicate: Predicate) => Predicate<any>
Checks whether a value is a string and contains at least one non-whitespace character
is.notBlank(''); // false
is.notBlank(' '); // false
is.notBlank('test'); // true
is.notBlank({toString: function() { return 'test'; }}); // false - since values are not converted to strings
Signature
is.notBlank(value: any) => boolean
Checks whether value is an array and is not empty
is.notEmptyArray([1]); // true
is.notEmptyArray([]); // false
is.notEmptyArray('string'); // false
Signature
is.notEmptyArray<T = any>(value: any) => boolean
Checks whether a value is null
is.null(null); // true
is.null({}); // false
Signature
is.null(value: any) => boolean
Checks whether a value is a number
is.number(10); // true
is.number('10'); // false
Signature
is.number(value: any) => boolean
Checks whether a value is an object and ignores null
is.object({}); // true
is.object('object'); // false
Signature
is.object(value: any) => boolean
Checks whether every enumerable property of object satisfies a predicate
const isObjectOfStrings = is.objectOf(is.string);
isObjectOfStrings({key: 'value', key1: 'value'}); // true
// same as
is.objectOf(is.string, {key: 'value', key1: 'value'}); // true
isObjectOfStrings({key: 1, key1: 'value'}); // false
Signature
is.objectOf(predicate: Predicate | Function) => Predicate<any>
is.objectOf(predicate: Predicate | Function, value: Object) => boolean
is.objectOf(predicate: Predicate | Function, value?: Object, ...extraArgs: any[]) => boolean | Predicate<any>
Returns a function that checks whether a value is equal to one of allowed values Function compares values using === operator
const isAllowedToAccess = is.oneOf('ROLE_ADMIN', 'ROLE_USER');
// same as
// const isAllowedToAccess = is.in(['ROLE_ADMIN', 'ROLE_USER']);
isAllowedToAccess('ROLE_ADMIN'); // true
isAllowedToAccess('ROLE_ANONYMOUS'); // false
Signature
is.oneOf(...allowedValues: any[]) => Predicate<any>
Throws:
- Error - if 0 or 1 allowed value provided
Checks whether a value is a plain object. Plain object is an object of which prototype is Object.prototype or null
is.plainObject({property: 'value'}); // true
is.plainObject(new Object); // true
is.plainObject(Object.create(null)); // true
is.plainObject(new String('test')); // false
const Foo = function() {};
is.plainObject(new Foo); // false
Signature
is.plainObject(value: any) => boolean
Checks whether a value is a positive number
is.positive(10); // true
is.positive(-1); // false
Signature
is.positive(value: number) => boolean
Checks whether a value is a primitive.
Helpful links:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
- http://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/
NOTE! A primitive value wrapped by a corresponding object is not a primitive anymore
is.primitive('test'); // true
is.primitive(undefined); // true
is.primitive(10); // true
is.primitive(null); // true
is.primitive(false); // true
is.primitive(new Number(10)); // false
is.primitive(new String('test')); // false
is.primitive(new Boolean(true)); // false
is.primitive({}); // false
Signature
is.primitive<T = string | number | boolean | null | undefined>(value: T) => boolean
Checks whether a value of given property of an object satisfies a predicate
If you need to check more properties at a time use {@link structure}.
is.property('name', is.string, {name: 'Tommy'}); // true
is.property('name', is.string)({name: 'Tommy'}); // true
is.property('name', is.string, {name: 2}); // false - since 2 is not a string
is.property('name', is.string, {}); // false - since undefined is not a string
Signature
is.property(propertyName: string | Symbol, predicate: Predicate | Function) => Predicate<any>
is.property(propertyName: string | Symbol, predicate: Predicate | Function, object: Object, ...extraParams: any[]) => boolean
is.property(propertyName: string | Symbol, predicate: Predicate | Function, object?: Object) => boolean | Predicate<any>
Throws:
- TypeError - if predicate is not a function
- Error - if too few arguments provided
- TypeError - is property name is not a string or a symbol
Signature
is.regexp(value: any) => boolean
Checks whether a string starts with a given prefix
const isProfessor = is.startsWith('Prof. ');
isProfessor('Prof. Bend Ovah'); // true
// same as
is.startsWith('Prof. ', 'Prof. Bend Ovah'); // true
isProfessor('Dr. Here U\' Are'); // false
Signature
is.startsWith(prefix: string) => Predicate<string>
is.startsWith(prefix: string, value: any) => boolean
is.startsWith(prefix: string, value?: any) => boolean | Predicate<string>
Throws:
- TypeError - if prefix is not a string
- Error - if prefix is empty
Checks whether value is Set
Signature
is.set<T = any>(value: any) => boolean
Checks whether a value is strictly equal to expected value (uses === operator)
const mom = {};
const isMyMom = is.strictEqual(mom);
isMyMom(mom); // true - mom is only one. Remember about it...
// same as
is.strictEqual(mom, mom); // true
isMyMom({}); // false
Signature
is.strictEqual<T = any>(expected: T) => Predicate<T>
is.strictEqual<T = any>(expected: T, value: any) => boolean
is.strictEqual<T = any>(expected: T, value?: any) => boolean | Predicate<T>
Checks whether a value is a string
is.string('test'); // true
is.string({}); // false
Signature
is.string(value: any) => boolean
Checks whether an object satisfies predicates defined in structure
NOTE: All predicates defined in structure must be satisfied. If some of the properties are optional use undefinedOr
You shouldn't use this function to validate input from the user and expect complex report of what is invalid. There are few reasons for that:
- it's just a predicate (that always returns only true or false)
- breaks the design rule
See examples for inspiration how you can use structure
// Structure checkconst schema = {
name: String, // only string
phone: is.or(String, Number), // string or number
surname: is.undefinedOr(String) // optional
},
isPerson = is.structure(schema);
const person = {name: 'Tommy', phone: 80129292};
isPerson(person); // true
// same as
is.structure(schema, person); // true
isPerson({name: 'Tommy'});
// filteringconst people = [
{name: 'Prof. Bend Ovah', age: 55, sex: 'male'},
{name: 'Dr. Supa Kaki', age: 34, sex: 'female'},
{name: 'Prof. Anti Santy', age: 46, sex: 'male'}
];
const professors = people.filter(is.structure({
name: is.startsWith('Prof.')
}));
// [
// {name: 'Prof. Bend Ovah', age: 55, sex: 'male'},
// {name: 'Prof. Anti Santy', age: 46, sex: 'male'}
// ]
// duck typingconst isDuck = is.structure({
quack: is.function,
walk: is.function
});
isDuck({
say: function() { return 'woof! woof!';
}}); // not a duck
isDuck({
quack: function() { return 'quack!'; },
walk: function() { return 'tup tup tup'; }
}); // yep, it's a duck
Signature
is.structure(structure: { [name: string]: Predicate | Function }) => Predicate<any>
is.structure(structure: { [name: string]: Predicate | Function }, value: Object) => boolean
is.structure(structure: { [name: string]: Predicate | Function }, value?: Object, ...extraArgs: any[]) => boolean | Predicate<any>
Throws:
- TypeError - if structure is not an object
Checks whether value is Set
is.symbol(Symbol('test')); // true
is.symbol('test'); // false
Signature
is.symbol(value: any) => boolean
Checks whether a value is a boolean true
is.true(true); // true
is.true('true'); // false
Signature
is.true(value: any) => boolean
Checks whether a value is truthy
is.truthy(true); // true
is.truthy(1); // true
is.truthy(0); // false
Signature
is.truthy(value: any) => boolean
Checks whether value is thenable according to Promise A+ spec https://promisesaplus.com/ Useful to asses whether value might be used as promise.
is.thenable(Promise.resolve('test')); // true
is.thenable({then: () => {}}); // this is still a thenable (according to spec)
is.thenable({}); // false
Signature
is.thenable(value: any) => boolean
Checks whether a value is undefined
is.undefined(undefined); // true
is.undefined(0); // false
Signature
is.undefined(value: any) => boolean
Checks whether a value is undefined or satisfies given predicate Very useful to check optional arguments of function.
const isUndefinedOrString = is.undefinedOr(is.string);
isUndefinedOrString(undefined); // true
isUndefinedOrString('test'); // true
// same as
is.undefinedOr(is.string, undefined); // true
is.undefinedOr(is.string, 'test'); // true
isUndefinedOrString({}); // false
// simpler for common types
is.undefinedOr(String)(undefined); // true
is.undefinedOr(String)('test'); // true
Signature
is.undefinedOr<T = any>(predicate: Predicate | Function) => Predicate<T>
is.undefinedOr<T = any>(predicate: Predicate | Function, value: any) => boolean
is.undefinedOr<T = any>(predicate: Predicate | Function, value?: any) => boolean | Predicate<T>
Throws:
- TypeError - if provided predicate is not a function
Checks whether value is an instance of WeakMap
Signature
is.weakMap<K extends object = any, B = any>(value: any) => boolean
Checks whether value is an instance of WeakSet
Signature
is.weakSet<T = any>(value: any) => boolean
Sets description of predicate.
Underneath assigns a non-enumerable property to a given predicate
function customPredicate(value) {
// implementation
}
is.setDescription(customPredicate, 'some custom description')
is.getDescription(customPredicate); // 'some custom description'
Signature
is.setDescription<T extends Predicate>(predicate: T, desc: string) => T
Returns predicate description
is.getDescription(is.string); // 'a string'
function someCustomPredicate(value) {
// implementation
}
is.getDescription(someCustomPredicate); // 'satisfied custom predicate "someCustomPredicate"'
is.getDescription(function(value) {}); // 'satisfied custom predicate "anonymous"'
Signature
is.getDescription(predicate: Predicate) => string
Asserts that value satisfies given predicate, otherwise throws a given error with provided message
// if no message provided then description of the predicate will be taken
is.assert(is.string)(null) // Error('Assertion failed. Must be a string')
// simple types are mapped to predicates so they get the same description
is.assert(String)(null) // Error('Assertion failed. Must be a string')
is.assert(String)('string') // undefined - everything is fine
is.assert(is.not(is.empty), 'Value is required')(''); // Error('Value is required')
// custom error class allowed
is.assert(String, undefined, CustomErrorClass)(null); // CustomErrorClass('Assertion failed. Must be a string');
Signature
is.assert(predicate: (Predicate | Function), message?: string, exceptionClass: { new (message: string): any } = Error) => (value: any, ...extraArgs: any[]) => void
A function that returns true or false based on input arguments
type Predicate<T = any> = (value: T, ...extraArgs: any[]) => boolean;
A function that returns true or false based on input arguments but additionally is a TypeGuard for Typescript compiler
type TypeGuardPredicate<T = any> = (value: any, ...extraArgs: any[]) => value is T;