DEV Community

loading...
Cover image for Curry, code, and databases

Curry, code, and databases

Ben Doty
・2 min read

You may have heard of curry, it's a type of food. People eat curry, and they may or may not like it. There is also a concept in programming called currying, and there is a lot to like about it.

The curry part

A curried function is a function that uses partial functions as it's arguments. It's a large part of functional programming and allows for better composition of software.

Here is an example

const add = a => b => a + b;
Enter fullscreen mode Exit fullscreen mode

You may notice that there are two arrow functions. That is how you curry. You take the first parameter, a, and it creates a partial function that is used as an argument for the second parameter b.

These are functionally equivalent:

// Curried add
const add = a => b => a + b;

// Regular add
const add = (a,b) => a + b;
Enter fullscreen mode Exit fullscreen mode

However, the curried version is a lot more diverse because of the partial function it creates.

const add = a => b => a + b;

add(1) // --> function
add(1)(2) // --> 3

// The first function is called, a partial function is created, 
// and then it's passed to the second for the final calculation.
Enter fullscreen mode Exit fullscreen mode

We can use that partial function to create "presets".

// Create preset using curried add function above
const add5 = add(5); // Partial function with 5 stored as variable 'a'

const add5(5) // --> 10
Enter fullscreen mode Exit fullscreen mode

You can start to see how this is powerful.

The database part

A little while ago I made a Mongodb library for my own use because I was annoyed with the default driver. I used currying to create a really simple API and I just released it on NPM for everyone to use.

It's called mongo-curry. It supports ES6 syntax, is super easy to test, and is just a really nice little library

If you want to try it, you can install it with

npm install mongo-curry

or

yarn add mongo-curry

Of course you need to know how to use it, so here is the docs

The last part

I hope you found something here helpful.

If you have some ideas on how to improve either the documentation, or the library, or would like to hear more about functional JavaScript please let me know.

Writing and publishing the library and documentation took a couple weeks worth of work. If you find it helpful and would like to see me make more stuff you can buy me a coffee

Discussion (0)

Forem Open with the Forem app