Functional Programming: Refactoring Global Variables Out of Functions
Randy Rivera
Posted on June 21, 2021
- So far, we have seen two distinct principles for functional programming:
Don't alter a variable or object - create new variables and objects and return them if need be from a function.
Declare function parameters - any computation inside a function depends only on the arguments passed to the function, and not on any global object or variable.
Let's rewrite the code so the global array
bookList
is not changed inside either function. Theadd
function should add the givenbookName
to the end of the array passed to it and return a new array (list). Theremove
function should remove the givenbookName
from the array passed to it.Note: Both functions should return an array, and any new parameters should be added before the
bookName
parameter.
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
// Change code below this line
function add (bookName) {
bookList.push(bookName);
return bookList;
// Change code above this line
}
// Change code below this line
function remove (bookName) {
var book_index = bookList.indexOf(bookName);
if (book_index >= 0) {
bookList.splice(book_index, 1);
return bookList;
// Change code above this line
}
}
var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
console.log(bookList);
- Answer:
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];
function add (books, bookName) {
let copyBooks = [...books] <--- we used a copy of the array in our functions.
copyBooks.push(bookName);
return copyBooks ;
}
function remove (books, bookName) {
let copyBooks = [...books]
var book_index = copyBooks.indexOf(bookName); // <-- is just finding if the book exists in the copyBooks(bookList) in this case for `newestBookList` book_index would be on position 1.
if (book_index >= 0) { // <-- (1 >= 0)
copyBooks.splice(book_index, 1); // <-- (1, 1) removes 'On The Electrodynamics of Moving Bodies'
return copyBooks;
}
}
var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');
console.log(newestBookList); // will display ["The Hound of the Baskervilles", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae", "A Brief History of Time"]
Posted on June 21, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
June 21, 2021