From 9479b61c09795997896bfa8eeaa2597a3fec1a9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Lemaire?= Date: Thu, 17 Oct 2019 23:26:50 +0200 Subject: [PATCH] Added "not" --- README.md | 6 +++++- package.json | 2 +- src/index.test.ts | 15 ++++++++++++++- src/index.ts | 6 ++++++ 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2a27f5d..6d31bf7 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ always() // => true never() // => false ``` -**and** and **or** combines predicates +**and**, **or** and **not** allow to combine or negate predicates ```typescript const a = and((x: number) => x > 2, (x: number) => x < 5); @@ -38,6 +38,10 @@ o(1) // => true o(2) // => false o(3) // => false o(4) // => true +const n = not((x: number) => x == 1); +n(0) // => true +n(1) // => false +n(2) // => true ``` **attr** gets an object's attribute: diff --git a/package.json b/package.json index fa0f3db..6afedd6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tk-functional", - "version": "0.2.0", + "version": "0.2.1", "description": "Typescript/Javascript helpers for functional-style programming", "source": "src/index.ts", "main": "dist/tk-functional.umd.js", diff --git a/src/index.test.ts b/src/index.test.ts index 6df142f..da1ff89 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -1,4 +1,4 @@ -import { always, and, attr, bool, cmp, fmap, identity, is, isinstance, never, nn, nnu, nop, nu, or, partial, pipe } from "./index"; +import { always, and, attr, bool, cmp, fmap, identity, is, isinstance, never, nn, nnu, nop, not, nu, or, partial, pipe } from "./index"; describe(nop, () => { it("does nothing", () => { @@ -52,6 +52,19 @@ describe(never, () => { }); }); +describe(not, () => { + it("negates predicate", () => { + const iseven = (x: number) => x % 2 == 0; + const isodd = not(iseven); + expect(iseven(0)).toBe(true); + expect(isodd(0)).toBe(false); + expect(iseven(1)).toBe(false); + expect(isodd(1)).toBe(true); + expect(iseven(2)).toBe(true); + expect(isodd(2)).toBe(false); + }); +}); + describe(and, () => { it("combines predicates", () => { const f = and((x: number) => x % 2 == 0, (x: number) => x > 5); diff --git a/src/index.ts b/src/index.ts index eadd832..7ccdafa 100644 --- a/src/index.ts +++ b/src/index.ts @@ -48,6 +48,12 @@ export const always = (...args: any[]) => true */ export const never = (...args: any[]) => false +/** + * Negate a predicate + */ +export function not(predicate: (...args: A) => boolean): (...args: A) => boolean { + return (...args) => !predicate(...args); +} /** * Apply a boolean "and" to merge predicates