Imagine we're getting a list of users from an API:
const users = getUsers();
// [{ id, name, location, ... }, ...]
We can do quite a complex processing using Undercut pipelines, but what if we need only to do something quick: like grouping users by a location and just passing the result further? Even calling pull
may be too much:
sendPreview(pullArray([groupBy(u => u.location)], users));
A case with a variable may be distracting too:
const usersByLocation = pullArray([groupBy(u => u.location)], users);
sendPreview(usersByLocation);
Fortunately, Undercut operations are framework-agnostic, which means they work by themselves. An operation is just a functions doing something on an Iterables. Arrays are Iterables, so our users
fit just right and groupBy(u => u.location)(users)
will return grouped users:
sendPreview(groupBy(u => u.location)(users));
Now it's better as we have no noise like pullArray
and square brackets.
There's another use case: you can define selectors using operations like so:
const groupUsers = groupBy(u => u.location);
// And use later:
const usersByLocation = groupUsers(users);
I have specifically chosen groupBy
because with even shorter actions you will likely go with plain Array methods and Arrow Functions:
render(users.filter(u => u.active));
But if you do need more serious job like flatMap
/groupBy
/orderBy
/etc or already using Undercut in other places, consider reusing from the Undercut or your own custom operations.
Undercut docs: undercut.js.org
Previous post: Lazy data processing using Undercut
Top comments (0)