Don't fear FP, embrace it instead.
A function is a process which takes some input, called arguments, and produces some output called a return value.
fn(in) => out
Function Declaration
sum(4, 9); // 13
function sum(a, b) {
return a + b;
}
sum(4, 9); // 13
Function Expression
sum(1, 3); // TypeError: undefined is not a function
const sum = function(a, b) {
return a + b;
}
sum(1, 3); // 4
Arrow functions
const arrowFunction = () => console.log('arrow function');
// is almost the same as
const regularFunction = function() {
console.log('regular function')
}
Functions are "first-class" objects
function doThis(fn) {
fn();
}
function giveMeAFunction() {
return () => console.log('I am a function');
}
A function which takes a function as an argument, returns a function, or both.
Definition
Definition
The very opposite of a pure function
"A dead giveaway that a function is impure is if it makes sense to call it without using its return value. For pure functions, that’s a noop."
let sum = function(a, b) {
return a + b;
};
let result = sum(1, 2);
var value1 = 1;
var value2 = 2;
let sum = function (a, b) {
return a + b;
};
let result = sum(value1, value2);
const value1 = 1;
var b = 2;
let sum = function (a, b) {
return a + b;
};
let result = sum(value1, b);
let a = 0;
let b = 1;
let sum = function(a, b) {
return a = a + b;
}
let result = sum(a, b);
let a = 0;
let inc = function (a) {
return a++;
}
let result = inc(a);
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];
let map = function (array) {
for (var i = 0; i < array.length; i++) {
setTimeout(() => array[i]++, 0);
}
return array;
}
let result = map(array);
const immutable = { a: 1, b: 2, c: 3 };
function mutate(object) {
return object;
}
let result = mutate(immutable);
const array = [8, 4, 1, 6, 8, 0];
function sort(list) {
console.log("sorted:" + (list = list.slice().sort()));
return list;
}
let result = sort(array);
function log() {
console.log("Hello World");
}
function doSomething(fn) {
if (1 === 0) {
fn();
}
return 1;
}
let result = doSomething(log);
function doNothing(fn) {
return fn;
}
let result = doNothing(Math.random);
function getDocument() {
return global.window.document;
}
getDocument()
let result = getDocument();
function divide(dividend, divisor) {
if (divisor === 0) throw new Error("Can't divide by 0.");
return dividend / divisor;
}
let result = divide(1, 1);
How to get from an impure to a pure function ?
Is a conversion always possible ?
"... using shared state being reliant on sequences which vary depending on indeterministic factors, the output is impossible to predict, and therefore impossible to test properly ..."
"non-determinism = parallel processing + mutable state"