Created by Ranjith Nair
'use strict';
function imperativeSquare(arr) {
/* You have to specify the followings :
1. How to loop throgh the array
2. The order of looping
3. Logic
*/
for (var i = 0; i < arr.length; i++) {
arr[i] *= arr[i];
}
return arr;
}
var a = [1, 2, 3, 4, 5];
console.log(imperativeSquare(a)); // [1, 4, 9, 16, 25]
See the Pen YVWmdo by Ranjith (@ranjithnair) on CodePen.
'use strict';
function declarativeSquare(arr) {
/* You have to specify the followings :
1. Logic
*/
return arr.map((val) => val*val);
}
var a = [1, 2, 3, 4, 5];
console.log(declarativeSquare(a)); // [1, 4, 9, 16, 25]
// A function with a side effect
var x = 10;
const myFunc = function ( y ) {
x = x + y;
};
myFunc( 3 );
console.log( x ); // 13
myFunc( 3 );
console.log( x ); // 16
// Make the global variable local.
const myFunc = function ( y ) {
const x = 10;
return x + y;
}
console.log(myFunc( 3 )); // 13
console.log(myFunc( 3 )); // 13
Combine functions to form new functions
// The function addThenSquare is made by combining the functions add and square.
const add = function ( x, y ) {
return x + y;
};
const square = function ( x ) {
return x * x;
};
const addThenSquare = function ( x, y ) {
return square(add( x, y ));
};
See the Pen Currying by Ranjith (@ranjithnair) on CodePen.
render() {
return (
{renderIf(1 + 2 === 3)(
This works!
)}
);
}
const renderIf = predicate => element => predicate && element;
See the Pen Immutability by Ranjith (@ranjithnair) on CodePen.
DAG - Structural Sharing
Array & Objects: HAT-Trie
See the Pen Map, Reduce & Filter by Ranjith (@ranjithnair) on CodePen.