Functional programming: A step to become funky!

As you know, functional programming is becoming more and more popular. There are multiple reasons for that: the code can be mathematically verified, asynchronous programming is far more elegant and etc.

Therefore, our guys have created and optimized some of the basic things in order to bring JS closer to being a functional language and accelerate the development processes. So we want to show you some examples of our challenges and solutions presented by one of our team members.

1) Optionzjs:

Challenge: Any variable can have no value (null). It means that you should be extra careful with your code.Solution: We made a construct that allows to obtain a value out of it only when a code for a ‘nothing’ variant processing is provided.

2) tryjs:

Challenge: There is a function, and it can handle certain parameters. But sometimes the function does not know how to interact with unexpected arguments. So, one needs some sort of exception handling – the transfer of information about such an unexpected situation. The error handling in JS (inherited from the C-like languages) uses a hard-to-read try-catch construct: the code “bounces” and has to have the “happy part” (the try block, where an exception might occur, but is not handled) alongside with the “sad part” (the catch block, where an exception is to be handled). In other words, the code is unclear and difficult to read. This library could help to handle these functions.

Solution: Similarly to the Optionzjs, we made a construct that allows to obtain a value out of it only when a code for exception processing is provided.

3) Clazjz:

Challenge 1:  As everyone knows, there are no classes in JS. Therefore, each developer has to describe their own types in pseudo “classes”, which wastes quite a bit of our precious time (especially when it gets to multiple inheritances).

Solution 1: Our developers made a library for personal convenience that allows one to declare “classes” and mix-in them together (to compose a class).

Challenge 2: Another feature is the absence of JS hidden properties of an object. It is impossible (before ES6 hath come) to have a property in an object, but at the same time to make it inaccessible from other functions, but the ones, “contained” in the object.

Solution 2: Using the closure feature the hidden properties can be imitated: functions can refer to the variables in their lexical scope. The clazjs claz.claz function returns a factory function for objects of the “class” type. This factory function declares private state variable, which is accessible from the methods inside the objects, created in this factory function. In other words, each object, created by a “class” (declared via claz.claz) is able to access its own, unique private state object.

Author: Serhiy Onyschsenko
Atlassian Team at Rozdoum

Posted 2015-03-23 02:03 in

Go back