Declarative Optional.Js
Muthukumaran
Posted on January 3, 2022
I have created a small Functional programming library in javascript , which supports developing code by chaining asynchronous and synchronous operations.
Consider this example
function getFromUserService({username, password}) {
return new Promise((function (resolve) {
resolve({name: "user", isAdmin: true})
}))
}
async function login(input) {
if (null == input) {
throw new Error("Input Cannot be Null")
}
const {username, password} = input
if (null == username || null == password) {
throw new Error("Input Cannot be Null")
}
const result = await getFromUserService(username, password)
if (result.isAdmin) {
redirectTo("adminPage")
} else {
redirectTo("userPage")
}
}
The same can be rewritten as
const page = await Optional.of(input)
.filter(({username, password}) => (null != username && null != password))
.map(getFromUserService)
.map(result => result.isAdmin ? "adminPage" : "userPage")
.toAsync();
page.ifPresentOrElse(redirectTo, () => {
throw new Error("Input Cannot be Null")
})
Using with Fetch
const rawResults = await fetch('https://jsonplaceholder.typicode.com/todos/' + item);
const response = await rawResults.json();
if (response.completed) {
return response.title
} else {
return null
}
The above can be rewritten as
return await Optional.of('https://jsonplaceholder.typicode.com/todos/' + item)
.map(fetch)
.map(response => response.json())
.filter(response => response.completed == true)
.map(response => response.title)
.getAsync();
Chaining of expressions enables the code concise and help to reasonate better, can easily be composed , combined.
Installation & Usage
npm install declarative-optional
//ES6
import Optional from "declarative-optional";
//Common Js
const Optional = require( "declarative-optional");
//Increment a Number , which may be null
Optional.of(input)
.map(val=>val+1)
.get()
💖 💪 🙅 🚩
Muthukumaran
Posted on January 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.