Functional Programming!

Using JavaScript

and Ramda.js

by Alex Voerman

What is functional programming?

Immutability

Lamdas

Functors

Currying

Monads

Monoids

λ

Closures

Partial Application

Programming Paradigms

Imperative Programming

Object Oriented Programming

Declarative Programming

(world view)
Series of commands in steps
Keep state in Objects that talk to each other
Describe what you want to do

Functional Programming

...is Coding with Pure Functions

Pure Function

Same inputs always return same output

No side effects

Is it pure?

let cart = {
  orders: [],
  orderTotal: 0
};

const addToCart = order => {
  cart.orders.push(order);
  cart.orderTotal += order.price;
};

addToCart({ name: 'tacos', price: 2.50 });
let cart = {
  orders: [],
  orderTotal: 0
};

const addToCart = (order, cartState) => {
  cartState.orders.push(order);
  cartState.orderTotal += order.price;

  return cartState; // pure functions should return something
};

addToCart({ name: 'tacos', price: 2.50 }, cart);
let cart = {
  orders: [],
  orderTotal: 0
};

const addToCart = (order, cartState) => {
  // return a new object
  return {
    orders: cartState.push(order),
    orderTotal: cartState.orderTotal + order.price
  };
};

addToCart({ name: 'tacos', price: 2.50 }, cart);
let cart = {
  orders: [],
  orderTotal: 0
};

const addToCart = (order, cartState) => {
  return {
    orders: [...cartState.orders, order], // <-- copies the array
    orderTotal: cartState.orderTotal + order.price
  };
};

addToCart({ name: 'tacos', price: 2.50 }, cart);
let cart = {
  orders: [],
  orderTotal: 0,
  startedDate: new Date(),
  userId: 10 // etc
};

const addToCart = (order, cartState) => {
  return {
    ...cartState, // <-- copies the cart object to new obj
    orders: [...cartState.orders, order],
    orderTotal: cartState.orderTotal + order.price
  };
};

addToCart({ name: 'tacos', price: 2.50 }, cart);

Arrays

Natvie JavaScript

FP Toolbox

  • use const instead of let and var
  • use map instead of forEach or a for-loop
  • use map, filter, reduce on arrays
  • use array spread [...x] to copy arrays
  • use object spread {...x} or Object.assign to copy objects

Why?

Testable

Predictable

Readable

Reusable

Debuggable

Okay, but what about currying...

and higher order functions

and hardcore "real" functional programming

Ramda

More

Ramda

Functional Programming

Functional JavaScript

By Alex Voerman

Functional JavaScript

  • 108