0% found this document useful (0 votes)
35 views

03-Functional Programming Exercises

The document provides examples and explanations of functional programming concepts like immutability, pure functions, and common utility functions like map, filter, find, and reduce. The immutability section demonstrates creating a new object instead of mutating existing objects. The pure functions section explains that pure functions always return the same output for the same input and do not modify arguments. The examples show how to use map to transform arrays, filter to remove items, find to get the first match, and reduce to aggregate items. Live code challenges practice applying these functions to arrays of numbers, strings, and objects.

Uploaded by

Aditya Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

03-Functional Programming Exercises

The document provides examples and explanations of functional programming concepts like immutability, pure functions, and common utility functions like map, filter, find, and reduce. The immutability section demonstrates creating a new object instead of mutating existing objects. The pure functions section explains that pure functions always return the same output for the same input and do not modify arguments. The examples show how to use map to transform arrays, filter to remove items, find to get the first match, and reduce to aggregate items. Live code challenges practice applying these functions to arrays of numbers, strings, and objects.

Uploaded by

Aditya Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Functional Programming Exercises

section 1: Immutability

understanding

Do not change any data; always return a new copy


In JavaScript, function arguments are references to actual data

challenge

1. Take an object with your mother’s name and your age. Now create an object for your sibling by
age difference.

Solution:
// code example
const tanay = { mother: 'Kanak', age: 32 }
const tanvi = { ...tanay, age: tanay.age - 4 }

console.log(tanvi) // { mother: "Kanak", age: 28 }


console.log(tanay) // { mother: "Kanak", age: 32 }
tanay === tanvi // false

// What NOT to do
const tanay = { mother: 'Kanak', age: 32 }
const tanvi = tanay // make a copy of tanay for tanvi
tanvi.age = tanay.age - 4 // then subtract the age for her
console.log(tanvi.age) // 28
console.log(tanvi) // { mother: "Kanak", age: 28 }
console.log(tanay) // { mother: "Kanak", age: 28 }
// We see here that tanay's object also changed. We don't want this.
// This copy method does not work.

COPY

2. Take an array with 5 colours. Create another array by adding 2 more colours to it.

Solution:
// code example

const colors = ['red', 'yellow', 'blue', 'green', 'orange']


const moreColors = [...colors, 'pink', 'purple']

colors === moreColors // false

console.log(colors) // ["red", "yellow", "blue", "green", "orange"]


console.log(moreColors) // ['red', 'yellow', 'blue', 'green', 'orange', 'pink', 'purple']

// What NOT to do

const colors = ['red', 'yellow', 'blue', 'green', 'orange']


const moreColors = colors
moreColors[5] = 'pink'
moreColors[6] = 'purple'
console.log(colors) // ['red', 'yellow', 'blue', 'green', 'orange', 'pink', 'purple']

console.log(moreColors) // ['red', 'yellow', 'blue', 'green', 'orange', 'pink', 'purple']

COPY

section 2: Pure functions

understanding

For the same input, the output will always be the same

Three rules

1. At least one argument


2. return a value or other function
3. Should not mutate any of its arguments —> Make a new copy

challenge

1. Write a function birthday() to take a person’s name and age in an object and then increase the
age by 1. Return the updated object.
const birthday = (person) => ({ ...person, age: person.age + 1 })

const person = { mother: 'Kanak', age: 32 }


const tanayAfterBirthday = birthday(person)
console.log(tanayAfterBirthday) // { mother: "Kanak", age: 33 }

person === tanayAfterBirthday // false

COPY

Live Challenge

1. Write an ES6 function increaseStock() to take a products’s name and quantity in an object and
then increase the quantity by 5.

Solution:
const increaseStock = (product) => ({
...product,
quantity: product.quantity + 5,
})

const product = { name: 'ruled notebook', quantity: 20 }


const inventoryStock = increaseStock(product)
console.log(inventoryStock) // { name: "ruled notebook", quantity: 25 }
COPY

section 2: Most used utility functions

understanding
Can take functions as arguments
Return Functions
Or both

exercise 01: map

understanding
To return a new array with modification on items
// syntax
map(functionThatTakesOneElementAtATime) // (element) => { /* … */ }
map(orFunctionThatTakesOneElemenAtATimeAndIndex) // (element, index) => { /* … */ }
function(item,index) COPY
// item ⇒ One item of the array
// index ⇒ index of the current item
// returns ⇒ new item for the new array
COPY

challenge

Live Code Example

1. Given an array of numbers, return a new array with square root of each number in it.

Solution:
// code example
const numbers = [1, 4, 9]
const roots = numbers.map((num) => Math.sqrt(num))
console.log(roots) // [1, 2, 3]
COPY
Live Challenges
1. Write an ES6 function that takes an array of numbers and returns an array with the square of
each element using the map method.

Solution:
const squareNumbers = (numbers) => numbers.map((number) => number * number)
const numbers = [1, 2, 3, 4, 5]
console.log(squareNumbers(numbers))
// Output:[1, 4, 9, 16, 25]
COPY

2. Write an ES6 function that takes an array of strings and returns an array with the length of each
string using the map method.

Solution:
const getLength = (stringsArray) => stringsArray.map((str) => str.length)
const stringsArray = ['neoG', 'coding', 'programming']
console.log(getLength(stringsArray))
// Output: [4, 6, 11]
COPY
will it work with objects?

Yes, this works with array of objects. But Not for objects.map

exercise 02: filter

understanding
remove items from an array based on a specific condition.
// syntax
filter((element) => {
/* … */
})
filter((element, index) => {
/* … */
})
array.filter(function(item, index)); COPY
// item => the current element of the array.
// index => the index of the current element
// return true if the item should be included, false otherwise
COPY

challenge

Live Code Example

1. Given an array, return an array with only odd numbers in it.


Solution:
// code example
const numbers = [3, 5, 6, 1, 2]
const isOdd = (num) => num % 2 !== 0
const oddArr = numbers.filter(isOdd)
console.log(oddArr) // [3, 5, 1]
COPY
Live Challenges

1. Given an array, return an array with only numbers divisible by 10.

Solution:
const arr = [5, 20, 15, 40, 3, 30, 11]
const divisibleBy10 = (num) => num % 10 === 0
const filteredArray = arr.filter(divisibleBy10)
console.log(filteredArray)
// Output: [20, 40, 30]
COPY

2. Write an ES6 function that returns an array with no number less than 10 in it.

Solution:
const getNumbersGreaterThanTen = (arr) => arr.filter((num) => num > 10)
const arr = [2, 20, 3, 30, 4, 40, 50, 5]
console.log(getNumbersGreaterThanTen(arr))
// Output: [20, 30, 40, 50]
COPY
exercise 03: find

understanding

used to find the first element in an array that satisfies a certain condition.
// syntax
find((element) => {
/* … */
})
find((element, index) => {
/* … */
})
array.find(function(element, index)); COPY
// element => the current element of the array.
// index => the index of the current element
// returns the first element in the array that satisfies the condition, otherwise undefined
COPY

challenge

Live Code Example


1. Write an ES6 function that takes an array, and returns the first even number in the array.

Solution:
const numbers = [5, 12, 8, 13, 44]
const isEven = (element) => element % 2 === 0
const findEvenNumber = numbers.find(isEven)

console.log(findEvenNumber) // 12
COPY
Live Challenges

1. Write an ES6 function that takes an array of fruits and returns the first fruit that is of 10
characters or above.

Solution:
const fruitArray = ['apple', 'banana', 'cherry', 'watermelon', 'pineapple']
const findLongFruit = (arr) => arr.find((str) => str.length >= 10)

console.log(findLongFruit(fruitArray))
// Output: "watermelon"
COPY
2. Given an array of objects, find the object with name “clips”.

Solution:
const inventory = [
{ name: 'socks', quantity: 12 },
{ name: 'shirts', quantity: 10 },
{ name: 'clips', quantity: 5 },
]

// Your code
const result = inventory.find(({ name }) => name === 'clips')
console.log(result) // { name: "clips", quantity: 5 }
COPY

exercise 04: reduce

understanding
// manual implementation
init1 = sumOfNumbers(init0, numbers[0])
init2 = sumOfNumbers(init1, numbers[1])
init3 = sumOfNumbers(init2, numbers[2])
COPY
used to "reduce" an array to a single value based on an accumulator and the items in the array.
// syntax
const callbackFn = (accumulator, currentValue) => {
/* … */
}
reduce(callbackFn)
reduce((accumulator, currentValue) => {
/* … */
}, initialValue)
array.reduce(function(accumulates, currentValue), initialValue) COPY
// accumulator => coming from the previous run
// currentValue => the current element of the array being processed.
// initialValue (optional) => the initial value of the total parameter. If this is not speci
// returns the updated value of the accumulator

COPY

challenge

Live Code Example

1. Given an array, find the sum of all numbers in the array using reduce() method.
// code example
const array = [1, 2, 3, 4]
const sumOfNumbers = (accumulator, currentValue, currentIndex) =>
accumulator + currentValue
const sum = array.reduce(sumOfNumbers, 0)
console.log(sum) // 10

COPY
Live Challenges

1. Given an array, find the sum of all odd numbers in the array using reduce() method.

Solution:
const array = [1, 2, 3, 4, 5, 6, 7]
const sumOfOddInd = (accumulator, currentValue, currentIndex) =>
currentValue % 2 !== 0 ? accumulator + currentValue : accumulator

console.log(array.reduce(sumOfOddInd, 0)) // 16
COPY

2. Write a function that takes an array of objects representing books with properties title, author,
and pages, and returns the total number of pages of all the books using the reduce function.
const books = [
{ title: 'The Alchemist', author: 'Paulo Coelho', pages: 197 },
{ title: 'To Kill a Mockingbird', author: 'Harper Lee', pages: 281 },
{ title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', pages: 180 },
]
const getTotalPages = (books) =>
books.reduce((totalPages, book) => totalPages + book.pages, 0)

console.log(getTotalPages(books)) // Output: 658

You might also like