And the best part is - the basic principles are actually simple!
Here are the 5 key FP concepts explained below
1. Data -> Calculations -> Actions
1. Data -> Calculations -> Actions
What your app does can be categorized as:
○ Data - facts about events
○ Calculations - computing input to output
○ Action - affects or is affected by the outside world
Making clear distinctions between the three will make your code better.
2. Pure functions
2. Pure functions
A pure function returns the same result when called with the same input, always. They're calculations that don't interact with the outside world.
Apply this concept in your code to make your functions predictable, and easy to understand and test.
3. Immutability
3. Immutability
In functional programming, you should never modify data. Instead, create a copy of it. Immutability means just that - data can't be mutated (modified).
Like pure functions, this principle makes your code more predictable and less error-prone.
4. Function composition
4. Function composition
In FP, complex behavior is achieved by combining calculations - using one function's result as another function's input in a chain-like manner.
This forces you to split large problems into smaller independent sub-problems, making your code simpler.
5. Currying
5. Currying
Currying allows you to partially apply arguments to a function. For instance:
add = (x, y) => x + y;
addTwo = add(2);
three = addTwo(1);
It doesn't come out of the box in JS, but you can achieve the same effect by creating higher-order functions or by using Ramda.
No comments:
Post a Comment
If you have any doubts or questions, please let us know.