Create Your Chainable Data Type
Have you ever wondered why then and catch work and how you could make one for your Data...
Enable Chaining of Any Type
We might all be familiar with chain syntax of Promises wherein to avoid callback hell we use then and catch methods
Ex:
fetch('https://...')
.then(res => log(res.data))
.catch(err => log(err))
But this might seem like magic but what if i tell you that there is a way you can get this functionality and chainable behavior for your custom functions...
If you think deeply you'll start to notice that chainable methods on Promise they are following a contract that no matter what it always precedes and succeeds a Promise and hence the behavior
Lets take a custom fn
const getNextChar = str => {
const trimmed = str.trim()
const number = parseInt(trimmed)
const nextNumber = Number(number + 1)
return String.fromCharCode(nextNumber)
}
console.log(getNextChar('64')) // Print 'A'
Now Before we start implementing our chainable we need to make sure to contain our data in a Defined Type
So say our contract is called Box
This is how its Abstract Data Type will look like
const Box = x => ({
chain: f => Box(f(x)),
fold: f => f(x)
})
chain
function on our Box will allow us to go on chaining methods to it and always guarantee that it adheres to Box
type
fold
function allows us to escape the Box and give the value it wraps around
So following this now I can convert the above getNextChar()
as chainable -
const getNextChar_ = str =>
Box(str)
.chain(x => x.trim())
.chain(parseInt)
.chain(num => Number(num + 1))
.fold(String.fromCharCode)
console.log(getNextChar_('64')) // Print 'A'
This is how by Defining a Contract that our Type must follow, we successfully made our custom str chainable and made it more Declarative!
This mapping of Data into its custom Box type and vice-versa is the foundation block of what we call Functors
in Programming Architecture
Now you know what to do when you want your data to be pipelined!
Impressive stuff isn't it <3