02 Functional programming

Lesson goal Understand what functional programming is: declarative development based on pure functions, in which a task is solved by a pipeline of small functions.

Functional programming is high-level, declarative development based on pure functions. Functional programming is a programming paradigm that relies on functions as its primary building blocks.

Pure functions are functions that return the same result for the same arguments and produce no side effects.

// ==== Note ===
// These examples may seem very confusing and unclear to you for now
// Don't worry, just keep reading

// our goal
// 1. Get the users whose status is online
// 2. Who are older than 20
// 3. Take the first user from the list
// 4. Get their name

// An example of functional code
// ready-made helpers from the Sanctuary library: in the course playground it is available as S,
// in your own project: import S from 'sanctuary'
const { pipe, prop, equals, filter, head, gt, map, fromMaybe } = S

// fetchAllUsers :: () -> Promise [Object]
const fetchAllUsers = () => new Promise(resolve => resolve([
  {
    name: 'John',
    status: 'online',
    age: 25
  },
  {
    name: 'Alex',
    status: 'offline',
    age: 18
  },
  {
    name: 'Angel',
    status: 'online',
    age: 18
  }
]))

const ONLINE = 'online'

// isStatus :: String -> (a -> Boolean)
const isStatus = status => pipe([
  prop('status'), // take the user's status field
  equals(status), // compare it with the status given above
])

// moreAge :: Number -> (a -> Boolean)
const moreAge = age => pipe([
  prop('age'), // take the age field
  gt(age), // check that the user's field is greater than age
])

// isStatusOnline :: a -> Boolean
const isStatusOnline = isStatus(ONLINE)

//  moreAge20 :: a -> Boolean
const moreAge20 = moreAge(20)

// getName :: a -> String
const getName = prop('name')

// Note: you don't have to build excessive abstractions,
// they can sometimes confuse your colleagues
// Ideally, of course, you would wrap the data in a monad so the composition doesn't crash
// when the server sends back something unexpected. That is protection at run time:
// TypeScript types on their own are checked only at compile time and don't protect against such data

// searchOnlineUsers :: [a] -> String
const searchOnlineUsers= pipe([
  filter(isStatusOnline), // keep only the users who are online
  filter(moreAge20), // keep the users older than 20
  head, // take the first user wrapped in Maybe: Just (user), or Nothing if the list is empty
  map(getName), // get that user's name inside the Maybe
  fromMaybe('') // take the name out of the Maybe; for Nothing it is ''
])

// program start
fetchAllUsers()
  .then(searchOnlineUsers)
  .then(name => console.log(name)) // 'John'

Key points

  • Functional programming is high-level, declarative development based on pure functions. Functions are its primary building blocks.
  • Pure functions return the same result for the same arguments and produce no side effects.
  • In the example, the task is solved by a pipeline of small functions built with pipe: keep the users who are online, then those older than 20, take the first one and get their name.
  • head returns a Maybe: Just (user), or Nothing if the list is empty. fromMaybe takes the value out of the Maybe and substitutes a fallback for Nothing.
  • You don't have to build excessive abstractions: they can sometimes confuse your colleagues.

Exercises

Exercise 1

Build a firstOfflineName pipeline out of small functions: it returns the name of the first user whose status is offline, or the string "nobody" if there is no such user. Use isStatus and getName from the starter and the Sanctuary functions filter, head, map and fromMaybe, as in the lesson. Check the pipeline on both lists.

Starter code

// ready-made Sanctuary helpers: in the course playground it is available as S
const { pipe, prop, equals, filter, head, map, fromMaybe } = S

const users = [
  { name: 'John', status: 'online' },
  { name: 'Alex', status: 'offline' },
  { name: 'Angel', status: 'online' },
]

// here every user is online
const onlineUsers = [
  { name: 'John', status: 'online' },
  { name: 'Angel', status: 'online' },
]

// isStatus :: String -> (a -> Boolean)
const isStatus = status => pipe([
  prop('status'),
  equals(status),
])

// getName :: a -> String
const getName = prop('name')

// firstOfflineName :: [a] -> String
// your code

console.log(firstOfflineName(users))
console.log(firstOfflineName(onlineUsers))

Expected output

Alex
nobody
Show solution
// ready-made Sanctuary helpers: in the course playground it is available as S
const { pipe, prop, equals, filter, head, map, fromMaybe } = S

const users = [
  { name: 'John', status: 'online' },
  { name: 'Alex', status: 'offline' },
  { name: 'Angel', status: 'online' },
]

// here every user is online
const onlineUsers = [
  { name: 'John', status: 'online' },
  { name: 'Angel', status: 'online' },
]

// isStatus :: String -> (a -> Boolean)
const isStatus = status => pipe([
  prop('status'),
  equals(status),
])

// getName :: a -> String
const getName = prop('name')

// firstOfflineName :: [a] -> String
const firstOfflineName = pipe([
  filter(isStatus('offline')), // only the users who are offline
  head, // the first of them in a Maybe: Just (user) or Nothing
  map(getName), // the name inside the Maybe
  fromMaybe('nobody'), // a fallback string for Nothing
])

console.log(firstOfflineName(users))
console.log(firstOfflineName(onlineUsers))

Playground

Write and run JavaScript right here — Ramda (R) and Sanctuary (S) are available.

Connected:
playground
Output
—