DEV Community

Cover image for Reusing operations for cleaner code
Anton Alexandrenok
Anton Alexandrenok

Posted on

Reusing operations for cleaner code

Imagine we're getting a list of users from an API:

const users = getUsers();
// [{ id, name, location, ... }, ...]
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

A case with a variable may be distracting too:

const usersByLocation = pullArray([groupBy(u => u.location)], users);

sendPreview(usersByLocation);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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)