object-predicate
TypeScript icon, indicating that this package has built-in type declarations

1.2.1 • Public • Published

object-predicate

Build Status Version

Use simple objects to represent predicates in JavaScript and TypeScript

Setup

npm install object-predicate

Why

Sometimes we need to be able to store a predicate as JSON data. Regex and function support added on top of this for convenience

Use

import { toPredicate } from 'object-predicate';
 
interface Character {
  name: string;
  age: number;
  occupation: string;
};
 
const characters: Character[] = [
  { name: 'Walter White',  age: 51, occupation: 'Chemistry Teacher' },
  { name: 'Gustavo Freng', age: 53, occupation: 'Restaurant Owner' },
  { name: 'Hank Schrader', age: 48, occupation: 'DEA Agent' },
  { name: 'Skyler White',  age: 47, occupation: 'Accountant' },
]
 
// Number predicate (greater-than, less-than, greater-or-equal, less-or equal)
const over50 = toPredicate({
  age: { gt: 50 }
});
const charactersOver50 = characters.filter(over50);
 
// Exact string match
const isAccountant = toPredicate({
  occupation: 'Accountant'
});
const accountants = characters.filter(isAccountant);
 
// Using a regex
const nameEndsWithWhite = toPredicate({
  name: /White$/
});
const whiteFamily = characters.filter(nameEndsWithWhite);
 
// Using a property predicate
const isDea = toPredicate({
  occupation: o => o.indexOf('DEA') >= 0
});
const deaAgents = characters.filter(isDea);

(c) 2018

Readme

Keywords

Package Sidebar

Install

npm i object-predicate

Weekly Downloads

0

Version

1.2.1

License

MIT

Unpacked Size

458 kB

Total Files

17

Last publish

Collaborators

  • northm