CyrefJS
CCyrefJS
فا
Back to documentation
Function/Since 1.38.0

negate

Creates a function that returns the boolean opposite of the result returned by the given function.

negate(fn):(...args: TArgs) => boolean

Parameters

fn(...args: TArgs) => booleanrequired

The function whose boolean result should be negated.

Returns

(...args: TArgs) => boolean

Returns a new function that returns the opposite boolean value of the original function's result.

Examples

01

Basic usage

The returned function reverses the boolean result.

TypeScript
const isEven = (value: number) => value % 2 === 0;

const isOdd = negate(isEven);

console.log(isOdd(3));
// true

console.log(isOdd(4));
// false
02

Negating a string predicate

A predicate that checks whether a string is empty can be negated to check whether it is not empty.

TypeScript
const isEmpty = (value: string) => value.length === 0;

const isNotEmpty = negate(isEmpty);

console.log(isNotEmpty("CyrefJS"));
// true

console.log(isNotEmpty(""));
// false
03

Passing multiple arguments

All arguments are forwarded to the original function before its result is negated.

TypeScript
const isGreater = (a: number, b: number) => a > b;

const isNotGreater = negate(isGreater);

console.log(isNotGreater(5, 3));
// false

console.log(isNotGreater(2, 4));
// true
04

Using with filter

The negated predicate can be used to select values that do not satisfy the original condition.

TypeScript
const isEven = (value: number) => value % 2 === 0;

const isOdd = negate(isEven);

const numbers = [1, 2, 3, 4, 5, 6];

const result = numbers.filter(isOdd);

console.log(result);
// [1, 3, 5]
05

Original function remains unchanged

negate creates a new function and does not modify the original function.

TypeScript
const isPositive = (value: number) => value > 0;

const isNotPositive = negate(isPositive);

console.log(isPositive(5));
// true

console.log(isNotPositive(5));
// false
Built with@cyref/js·Official documentation