pselect

0.1.0 • Public • Published

pselect

Safely select arbitrarily nested nullable fields (with strong types).

import { select } from "pselect";
 
const foo = {};
 
const baz = select(foo, p => p.bar.baz); // No Error!
console.log(baz); // undefined

How?

pselect uses the JavaScript Proxy object and Reflection to safely select the nullable field. If Proxy support doesn't exist (ex: due to an old browser), if gracefully falls back to the less effiecient, but always available try-catch.

Installing

npm install pselect

API

select

select takes in your subject and a selector function and returns the value or undefined.

const select: <TObj, TResult>(
  subjectTObj,
  selector(obj: TObj) => TResult
) => TResult;

Example:

import { select } from "pselect";
 
const foo = {};
 
const baz = select(foo, p => p.bar.baz); // No Error!
console.log(baz); // undefined

cselect

cselect is the curried version of the select function. It lets you write nice functional code that you can pipe and chain. (See example)

const cselect: <TObj, TResult>(
  selector(subject: TObj) => TResult
) => (subject: TObj) => TResult;

Examples:

import { cselect } from "pselect";
 
const foo = {};
 
const getBaz = p => p.bar.baz;
 
console.log(getBaz(foo)); // undefined
import { cselect } from "pselect";
 
interface IPerson {
  name: string;
  identification?: {
    passport?: {
      passportNumber: "111";
    };
  };
}
 
const getPerson = (id: number) => {
  return people.find(...);
}
 
const passportNumber = pipe(
  getPerson,
  cselect(p => p.identification!.passport!.passportNumber),
  passportNumber => passportNumber || "NO_PASSPORT"
);
 
const fred: IPerson = {
  name: "fred"
};
 
passportNumber(fred); // NO_PASSPORT

Prior Art

Licence

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i pselect

Weekly Downloads

1

Version

0.1.0

License

MIT

Unpacked Size

5.95 kB

Total Files

14

Last publish

Collaborators

  • ncthis