DEV Community

Muthukumaran
Muthukumaran

Posted on

Declarative Optional.Js

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

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

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

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();

Enter fullscreen mode Exit fullscreen mode

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()

Enter fullscreen mode Exit fullscreen mode

Links
npm
github

Top comments (0)