Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Advanced JavaScript

You're reading from   Advanced JavaScript Speed up web development with the powerful features and benefits of JavaScript

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher
ISBN-13 9781789800104
Length 330 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Zachary Shute Zachary Shute
Author Profile Icon Zachary Shute
Zachary Shute
Arrow right icon
View More author details
Toc

Chapter 5: Functional Programming


Activity 5 – Recursive Immutability

You are building an application in JavaScript and your team has been told that it cannot use any third-party libraries for security reasons. You must now use Functional Programming (FP) principles for this application and you need an algorithm to create immutable objects and arrays. Create a recursive function that enforces the immutability of objects and arrays at all levels of nesting with Object.freeze(). For simplicity, you can assume that there are no null or classes nested in the objects. Write your function in activities/activity5/activity-test.js. This file contains code to test your implementation.

To demonstrate forcing immutability in objects, follow these steps:

  1. Open the activity test file at activities/activity5/activity-test.js.

  2. Create a function called immutable that takes in a single argument, data.

  3. Check to see if data is not of type object. If it is not, then return.

  4. Freeze the data object. You don't need to freeze non-objects.

  5. Loop through the object values with object.values and a forEach() loop. Recursively call the immutable function for each.

  6. Run the code contained in the test file. If any tests fail, fix the bugs and rerun the test

Code:

activity-solution.js
function immutable( data ) {
 if ( typeof data !== 'object' ) {
   return;
 }
 Object.freeze( data );
 Object.values( data ).forEach( immutable );
}

Snippet 5.11: Recursive immutability

Take a look at the following output screenshot below:

Figure 5.7 : Passed Tests output display

Outcome:

You have successfully demonstrated forcing immutability in objects.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image