@hs/transmute
provides convenient, composable functions for transforming Arrays, Immutable.js data structures, and Objects.
Transmute can be installed with npm
or yarn
.
npm install @hs/transmute
import { Map } from 'immutable';
import pick from 'transmute/pick';
// returns Map { one => 1, three => 3 }
pick(['one', 'three'], Map({one: 1, two: 2, three: 3}));
Most of the function (with the execption of some of the composition functions like compose
and pipe
) are curried to facilitate partial application. You might also notice that the argument order is the oposite of you'll find in other utility libraries. Passing the options and then the subject makes currying much more useful.
import { Map } from 'immutable';
import pick from 'transmute/pick';
const pickTwo = pick(['two']);
// returns Map { two => 2 }
pickTwo(Map({one: 1, two: 2, three: 3}));
transmute
also includes some helpful composition functions which are powerful when we combine them with curried transforms.
import { Map, Set } from 'immutable';
import * as t from 'transmute';
const setOfKeysWithEvenValues = t.pipe(
t.filter((val) => val % 2 === 0),
t.keySeq,
Set
);
// returns Set { 'two', 'four' }
takeEvenValues(Map({one: 1, two: 2, three: 3, four: 4}));
Creates a function that always returns returnValue
.
Parameters
returnValue
T
Examples
const alwaysBlue = always('blue');
alwaysBlue() === 'blue';
Returns T
Sets a function's this
context. Similar to Function.prototype.bind
.
Parameters
Examples
bind(console.log, console);
Returns Function
Returns true
if the results of arg
applied to both condition1
and
condition2
are truthy.
Parameters
Examples
const isOneToTen = both(
n => n >= 1,
n => n <= 10
);
isOneToTen(3) === true;
isOneToTen(11) === false;
Returns boolean
Returns an empty copy of subject
.
Parameters
Examples
clear([1, 2, 3]) // returns []
clear(List.of(1, 2, 3)) // returns List []
clear({one: 1, two: 2, three: 3}) // returns {}
Returns (Array | Collection | Object)
Create a function that runs operations from right-to-left.
compose
is not curried.
Parameters
Examples
const doubleAndTakeEvens = pipe(
filter(n => n % 2 === 0),
map(n => n * 2)
);
doubleAndTakeEvens(List.of(1, 2, 3))
// returns List [ 2, 4, 6 ]
Returns Function
Returns the number of values in subject
.
Parameters
subject
TYPE
Examples
count(List.of(1, 2, 3)) === 3;
Returns number
Creates a curried version of operation
.
Parameters
operation
Function
Examples
const toArray = curry((a, b, c) => [a, b, c]);
const toArrayWith1 = toArray(1);
toArrayWith1(2, 3) === [1, 2, 3];
Returns Function
Create a curried version of operation
that expects arity
arguments.
Inception-ally, curryN
is also curried.
Parameters
Examples
const toArray = curryN(3)((...args) => [...args]);
toArray(1, 2, 3) === [1, 2, 3];
Returns Function
operation
is called interval
milliseconds after the most recent call.
Parameters
Returns any the most recent result of operation
src/debounceImmediate.js:52-52
operation
is called immediately and then interval
milliseconds after the most
recent call.
Parameters
Returns any the most recent result of operation
Take the difference between one iterable and another iterable. Only the elements present in just subject will remain.
Parameters
toRemove
Iterablesubject
Iterable
Examples
const removeOne = difference(Set.of(1));
removeOne(Set.of(1, 2, 3)) // returns Set { 2, 3 }
Returns Iterable
Returns true if the results of arg
applied to either first
or second
are truthy.
Parameters
Examples
const oneOrTwo = either(
n => n === 1,
n => n === 2
);
oneOrTwo(1) === true;
oneOrTwo(2) === true;
oneOrTwo(3) === false;
Returns boolean
Get a Seq of the entries (i.e. [key, value] tuples) in subject
.
Parameters
Examples
entrySeq(Map({one: 1, two: 2}))
// returns Seq [ ['one', 1], ['two', 2] ]
Returns Seq
Returns true
if all items in subject
match predicate
.
Parameters
predicate
Function returnstrue
if item is a match.subject
Iterable
Examples
const alwaysBlue = every(v => v === 'blue');
alwaysBlue(List.of('blue', 'blue')) === true;
alwaysBlue(List.of('red', 'blue')) === false;
Returns bool
Remove values for which predicate
returns false
.
Parameters
predicate
Function returnstrue
if a value should be included.subject
Iterable to filter.
Examples
// returns List [ 2 ]
filter(
(n) => n % 2 === 0,
List.of(1, 2, 3)
);
Record
s have a fixed set of keys, so filter returns a Map instead.
// returns Map { 'one' => 1, 'three' => 3 }
filter(
(n) => n % 2 === 0,
ThreeRecord({one: 1, two: 2, three: 3})
);
Returns Iterable without values that didn't match predicate
.
Remove values for which predicate
returns true
.
Parameters
predicate
Function returnstrue
if a value should be excluded.subject
Iterable to filter.
Examples
// returns List [ 1, 3 ]
filterNot(
(n) => n % 2 === 0,
List.of(1, 2, 3)
);
Returns Iterable without values that matched predicate
.
Flattens an iterable as deeply as possible.
Parameters
subject
Iterable
Examples
// return List [ 1, 2, 3, 4, 5, 6 ]
flatten(List.of(List.of(1, List.of(2, 3)), List.of(4, 5, 6)));
Returns Iterable
Flattens an iterable depth
levels.
Parameters
depth
numbersubject
Iterable
Examples
// return List [ 1, List [ 2, 3 ], 4, 5, 6 ]
flattenN(1, List.of(List.of(1, List.of(2, 3)), List.of(4, 5, 6)));
Returns Iterable
Executes effect
for each value in subject
, then returns subject
.
Parameters
effect
Functionsubject
TYPE
Examples
forEach(
v => console.log(v),
Map({ one: 1, two: 2, three: 3 })
);
// prints...
// 1
// 2
// 3
Returns TYPE
A version of Immutable.fromJS that drops all but the first argument for
compatibility with other transmute functions like map
.
Parameters
json
any
Examples
fromJS({items: [1, 2, 3]})
// returns Map { items: List [ 1, 2, 3 ] }
Returns Iterable?
Retrieve the value at key
from subject
.
Parameters
key
any to lookup insubject
.subject
(Iterable | Object) in which to look upkey
.
Examples
// returns 1
get('one', Map({one: 1, two: 2, three: 3}))
Returns any the value at key
.
Retrieve a keyPath
from a nested Immutable or JS structure.
getIn
short circuts when it encounters a null
or undefined
value.
Parameters
Examples
const getFirstName = getIn(['name', 'first']);
const user = UserRecord({
name: Map({
first: 'Test',
last: 'Testerson',
}),
});
getFirstName(user) === 'Test'
Returns any
Returns true
if key
exists in subject
.
Parameters
Examples
const hasOne = has('one');
hasOne({one: 1}) === true;
hasOne(Map({two: 2})) === false;
Returns boolean
Returns true
if keyPath
is defined in a nested data structure.
hasIn
short circuts and returns false
when it encounters a null
or undefined
value.
Parameters
Examples
const hasFirstName = hasIn(['name', 'first']);
const user = UserRecord({
name: Map({
first: 'Test',
last: 'Testerson',
}),
});
hasFirstName(user) === true
Returns boolean
Returns it's first argument.
Parameters
thing
any
Examples
identity('something') === 'something'
Returns any
Applies affirmative
to subject
if predicate(subject)
is truthy.
Otherwise applies negative
to subject
.
Parameters
Examples
const incrementAwayFromZero = ifElse(
n => n >= 0,
n => n + 1,
n => n - 1
);
incrementAwayFromZero(1) === 2
incrementAwayFromZero(-1) === -2
Returns any
Applies affirmative
to subject
if predicate(subject)
is truthy.
Otherwise returns subject
.
Parameters
Examples
import ifThen from 'transmute/ifThen';
const toJS = ifThen(
subject => typeof subject.toJS === 'function',
subject => subject.toJS
);
toJS(List.of(1, 2, 3)) //=> [1, 2, 3]
toJS([1, 2, 3]) //=> [1, 2, 3]
Returns any
Create a Map, or OrderedMap from subject
with a key for each item
returned by keyMapper
.
Parameters
keyMapper
Function generates keys for each itemsubject
Iterable to index
Examples
indexBy(get('id'), List.of({id: 123}, {id: 456}))
// returns Map { 123: {id: 123}, 456: {id: 456} }
Returns KeyedIterable
Get a Seq of the keys in subject
.
Parameters
Examples
keySeq({one: 1, two: 2, three: 3})
// returns Seq [ 'one', 'two', 'three' ]
Returns Seq
Create a new Iterable by applying mapper
to each item in subject
.
Parameters
mapper
Function applied to each item insubject
.subject
Iterable the Iterable to map.
Examples
// returns List [ 2, 3, 4 ]
map(
(val) => val + 1,
List.of(1, 2, 3)
);
Returns Iterable with each value of subject
updated with mapper.
Transform the contents of subject
to into
by applying operation
to each
item.
Parameters
into
anyoperation
Functionsubject
Iterable [description]
Examples
reduce(
List(),
(acc, val) => acc.push(val),
Map({ one: 1, two: 2, three: 3 })
);
// returns List [ 1, 2, 3 ]
Returns Iterable
Returns a copy of subject
with key
set to value
.
Parameters
Examples
set('one', 2, {one: 1});
// returns {one: 2}
Returns (Array | Iterable | Object)
Returns true
if any items in subject
match predicate
.
Parameters
predicate
Function returnstrue
if item is a match.subject
Iterable
Examples
const anyBlue = some(v => v === 'blue');
anyBlue(List.of('blue', 'red')) === true;
anyBlue(List.of('red', 'red')) === true;
Returns bool
Sort subject
according to the value returned by getSortValue
.
Parameters
getSortValue
Function returns a value to sort on for each item insubject
.subject
(Array | Iterable | Object) the thing to sort.
Examples
// returns List [ 2, 1, 3 ]
sortBy(
(n) => n % 2,
List.of(1, 2, 3)
);
// returns OrderedMap { "one" => 1, "two" => 2, "three" => 3 }
sortBy(
(n) => n % 2,
Map({three: 3, one: 1, two: 2})
);
Returns Iterable an ordered version of subject
(e.g. sorting a Map
returns an OrderedMap
).
Get a Seq of the values in subject
.
Parameters
Examples
valueSeq(Map({ one: 1, two: 2, three: 3 }))
// returns Seq [ 1, 2, 3 ]
Returns Seq
Returns true
if value is an Array.
Parameters
value
any
Returns boolean
Returns true if value
is "empty".
If given null, undefined, isEmpty will return true.
Parameters
value
any
Returns boolean
Returns true if value
is a Function.
Parameters
value
any
Returns boolean
Returns true if value
is an instance of Constructor
.
Parameters
Constructor
Functionvalue
any
Returns boolean
Returns true
if subject
is null
.
Parameters
subject
any
Returns boolean
Returns true
if subject
is a JavaScript Number and not NaN
.
Parameters
value
any
Returns boolean
Returns true if value
is an Object.
Parameters
value
any
Returns boolean
Returns true
if subject
is an instance of a Record.
Parameters
subject
any
Returns boolean
Returns true if value
is a String.
Parameters
value
any
Returns boolean
Returns true
if subject
is undefined
.
Parameters
subject
any
Returns boolean
Like map
but transforms an Iterable's keys rather than its values.
Parameters
keyMapper
Function returns a new keysubject
KeyedIterable
Examples
Can be useful for converting keys of API results to a common type.
import { mapKeys, toString } from 'transmute';
const stringifyKeys = mapKeys(toString);
const m = Map.of(123, Map(), 456, Map(), 789, Map());
stringifyKeys(m).equals(Map.of('123', Map(), '456', Map(), '789', Map()));
Returns KeyedIterable
Returns true
if the key => value pairs in pattern
match the correspoding key => value pairs in subject
.
Parameters
Examples
const hasOneAndThree = match({one: 1, three: 3});
hasOneAndThree(Map({one: 1, two: 2, three: 3})) === true;
Returns boolean
Memoizer that uses a Map
to allow for arbitrarily many/complex keys.
Parameters
operation
Function to memoize.hashFunction
Function that generates the cache key. (optional, defaultdefaultHashFunction
)
Examples
const sum = memoize((list) => {
return list.reduce((total, n) => total + n, 0);
});
// does work and returns 15
sum(List.of(1, 2, 3, 4, 5))
// returns 15 but does no work
sum(List.of(1, 2, 3, 4, 5))
We can use the hashFunction
param to customize the key used in the cache.
const sum = memoize(
(list) => list.reduce((total, n) => total + n, 0),
(list) => return list.join('-')
);
It's also possible to inspect the state of an instance by reading the .cache
property.
const sum = memoize(...);
Map.isMap(sum.cache) === true;
Returns Function memoized version of operation
.
Like memoize, but only caches the most recent value. It's often useful for caching expensive calculations in react components.
Parameters
operation
Function
Examples
const sum = memoizeLast((...nums) => nums.reduce((acc, n) => acc + n));
sum(List.of(1, 2, 3))
//> does work, returns 6
sum(List.of(1, 2, 3))
//> takes cached value, returns 6
sum(List.of(4, 5, 6))
//> does work, returns 15
sum(List.of(1, 2, 3))
//> does work again, returns 6
Returns Function
Takes each entry of updates
and sets it on subject
.
Parameters
updates
Iterable key-value pairs to merge insubject
.subject
Iterable the thing to update.
Examples
// returns Map { "one" => 3, "two" => 2, "three" => 1}
merge(
Map({one: 1, two: 2, three: 3}),
Map({one: 3, three: 1})
);
Returns Iterable with each key-value of updates
merged into subject
.
Drop specified keys from a KeyedIterable (e.g. a Map
or OrderedMap
).
Parameters
keys
Array<any> to remove.subject
KeyedIterable from which to removekeys
.
Examples
// returns Map { "two" => 2 }
omit(
['one', 'three'],
Map({one: 1, two: 2, three: 3})
);
Returns KeyedIterable without keys
.
fn
is only run one time.
Parameters
fn
Function
Returns any the result of the first time fn
was called
Like fn.bind()
, but without the option to pass context
.
partial
is not curried.
const add = (a, b, c) => a + b + c; const add11 = partial(add, 5, 6); add11(7); // returns 18
Parameters
operation
Function the function to bind.first
any the first argument to pass tooperation
args
...any
Returns Function
Like transmute/partial
, but takes an Array or Iterable of arguments to pass
to operation
rather than a dynamic number of args. Unlike partial
it is
curried.
partial : partialApply :: Function.prototype.call : Function.prototype.apply
Parameters
operation
Function the function to bind.args
(Array | Iterable) ordered collection of arguments to bind tofn
.
Examples
const add = (a, b, c) => a + b + c;
const add11 = partialApply(add, [5, 6]);
add11(7); // returns 18
Returns Function
Select specified keys from a KeyedIterable (e.g. a Map
or OrderedMap
).
Parameters
Examples
// returns Map { "one" => 1, "three" => 3 }
pick(
['one', 'three'],
Map({one: 1, two: 2, three: 3})
);
Returns KeyedIterable with just keys
.
Create a function that runs operations from left-to-right.
pipe
is not curried.
Parameters
Examples
const takeEvensAndDouble = pipe(
filter(n => n % 2 === 0),
map(n => n * 2)
);
takeEvensAndDouble(List.of(1, 2, 3))
// returns List [ 4 ]
Returns Function
Select key
from each item in subject
.
Parameters
key
anysubject
Iterable
Examples
const pluckName = pluck('name');
pluckName(userMap) === Map({123: 'Testing'});
Returns Iterable
Creates a function identical to operation
but with length arity
.
Parameters
Examples
const op = (...args) => args;
op.length === 0;
const twoArgOp = setArity(2, op);
twoArgOp.length === 2;
Returns Function
Set the value
at keyPath
in a nested structure.
Parameters
Examples
setIn(['one', 'two'], 3, {one: {two: 2}});
// returns {one: {two: 3}}
Unset keyPaths will be set based on the most recent type.
setIn(['one', 'two'], 3, {});
// returns {one: {two: 3}}
setIn(['one', 'two'], 3, Map());
// returns Map { one => Map { two => 3 } }
Ensures operation
is only called once every interval
milliseconds.
Parameters
Returns any the most recent result of operation
Converts an Iterable to a native JS structure.
Parameters
subject
Iterable to convert.
Returns (Array | Object) native JS requivalent of subject
.
Converts subject
to a Seq
if possible.
Parameters
Returns Seq
Returns the value converted to a string.
Parameters
value
any
Returns a unique integer string appended to prefix
.
Parameters
prefix
string (optional, default''
)
Examples
uniqueId('test-') === 'test-1';
uniqueId('other-') === 'other-2';
uniqueId('test-') === 'test-3';
Sets the value at key
to the result of updater
.
Parameters
Examples
const incrementCount = update('count', n => n + 1);
incrementCount({count: 1});
// returns {count: 2}
Returns (Array | Iterable | Object)
Apply updater
to the value at keyPath
.
Parameters
keyPath
(Array<any> | Iterable<any>) the location whereupdater
should be applied.updater
Function the tranformation to apply.subject
(Array | Iterable | Object) the thing to update.
Examples
const incrementUserCount = updateIn(['users', 'count'], n => n + 1);
incrementUserCount({users: {count: 1}});
// returns {users: {count: 2}}
Unset keyPaths will be set based on the most recent type.
const incrementUserCount = updateIn(['users', 'count'], (n = 0) => n + 1);
incrementUserCount({});
// returns {users: {count: 1}}
incrementUserCount(Map());
// returns Map { users => Map { count => 1 } }
Returns (Array | Iterable | Object)
Takes items in subject
that match pattern
.
Parameters
pattern
Functionsubject
Iterable
Examples
const users = Map({
123: {id: '123', name: 'Jack'},
456: {id: '456', name: 'Jill'},
});
where({name: 'Jack'}, users);
// returns Map { 123: {id: '123', name: 'Jack'} }
Returns Iterable
Removes values in unwanted
from subject
.
Parameters
unwanted
Iterablesubject
Iterable
Examples
const removeOne = without(Set.of(1));
removeOne(Set.of(1, 2, 3)) // returns Set { 2, 3 }
Returns Iterable