Utility functions to convert instance methods's to context-free functions ready for use with esnext pipeline operator and point-free functional programming. Convert any x.whatever(...args)
to whatever(...arg)(x)
.
Read the documentation for more information
yarn add pipey
import { createPipe, createPipes, fromClassPrototype, compose } from 'pipey';
// Note: compose is a regular lodash-like compose function
import _ from 'pipey/proxy'; // For proxy-based api
const { map, filter } = fromClassPrototype(Array);
const doubleNumbers = map(x => x * 2);
const doubleOddNumbers = compose(doubleNumbers, filter(x => x % 2));
doubleOddNumbers([ 2, 3, 4, 5 ]); // Returns [ 6, 10 ]
const forEach = createPipe('forEach');
forEach(x => console.log(x))([ 1, 2, 3, 4 ]); // Logs 1 2 3 4
const { map, filter, split } = createPipes(['map', 'filter', 'split']);
const head = ([ first ]) => first;
const compact = filter(Boolean);
const getFirstNames = names =>
names
|> compact
|> map(split(' '))
|> map(head);
getFirstNames([ '', null, 'Akshay Nair', 'John Doe', 'Bruce Fucking Lee' ]); // Returns ['Akshay', 'John', 'Bruce']
A proxy based alternative api for pipey Read the documentation
import _ from 'pipey/proxy';
const getInitials = compose(
_.join(''),
_.map(_.charAt(0)),
_.split(' '),
_.$prop('name'), // $prop is a pre-defined plugin
);
getInitials({ name: 'Akshay Nair' }) === 'AN';
- Using with the amazing pipe operator
const { map, filter, reduce } = fromClassPrototype(Array);
const getInputData = () =>
document.querySelectorAll('.js-input')
|> map($input => [ $input.name, $input.value ])
|> filter(([_, value]) => value)
|> Object.fromEntries
|> Array.from;
getInputData(); // Returns something like { email: '[email protected]', name: 'Han Solo' }
- Working with collection methods
// Two ways to extract methods out (createPipes & fromClassPrototype)
const { map, filter } = fromClassPrototype(Array);
const { split } = createPipes(['split']);
const getFirstNames = compose(
map(xs => xs[0]),
map(split(' ')),
filter(Boolean),
);
getFirstNames([ '', null, 'Akshay Nair', 'John Doe', 'Bruce Fucking Lee' ]); // Returns ['Akshay', 'John', 'Bruce']
- Working with dom methods
const { forEach, join } = fromClassPrototype(Array);
const { setAttribute } = fromClassPrototype(HTMLInputElement);
const inputs = ['.js-input-name', '.js-input-email'];
inputs
|> join(', ')
|> (selector => document.querySelectorAll(selector))
|> forEach(setAttribute('disabled', 'disabled'));