<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ricardo Luz</title>
    <description>The latest articles on DEV Community by Ricardo Luz (@ricardo).</description>
    <link>https://dev.to/ricardo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F104533%2F899f7d1d-27b6-4a86-9961-ab48cb609557.jpeg</url>
      <title>DEV Community: Ricardo Luz</title>
      <link>https://dev.to/ricardo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ricardo"/>
    <language>en</language>
    <item>
      <title>The problem with Object.freeze</title>
      <dc:creator>Ricardo Luz</dc:creator>
      <pubDate>Wed, 22 Apr 2020 16:27:53 +0000</pubDate>
      <link>https://dev.to/ricardo/the-problem-with-object-freeze-4g25</link>
      <guid>https://dev.to/ricardo/the-problem-with-object-freeze-4g25</guid>
      <description>&lt;p&gt;In several situations, we need to ensure that some Object values and methods won’t change anymore; some examples are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  A list with access keys to external web services&lt;/li&gt;
&lt;li&gt;  An object with a unique ID that represents the user or current session&lt;/li&gt;
&lt;li&gt;  Information about the user device like the operating system, browser version and name and more.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To solve problems like this my first approach was relying upon in &lt;code&gt;Object.freeze&lt;/code&gt; function, let’s take an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myCustomObj = {  
  thisObjectWillChange: "nope ",  
};  

Object.freeze(myCustomObj);  

myCustomObj.thisObjectWillChange = "trying change this 🤔";  

console.log(myCustomObj.thisObjectWillChange); // will return: nope

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;So far so good, it worked as we expected, but something works weird when we increase the number of branches of our object tree-like in this example:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const accessKeys = {  
  aws: {  
   accessKeyId: 'abc123',  
   secretAccessKey: 'secretValue'  
 },  
 google: 'gogole123'  
}
Object.freeze(accessKeys);
accessKeys.aws.accessKeyId = 'trying to change this value 😰';

console.log(accessKeys.aws.accessKeyId); // will return 'trying to change this value 😰'

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;So, what’s happened wrong? Why the &lt;code&gt;Object.freeze&lt;/code&gt; won’t prevent this alteration? When we check the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze"&gt;MDN Documentation&lt;/a&gt; we found the answer:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;What is “shallow freeze”?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The result of calling &lt;code&gt;Object.freeze(object)&lt;/code&gt; only applies to the immediate properties of &lt;code&gt;object&lt;/code&gt; itself and will prevent future property addition, removal or value re-assignment operations only on &lt;code&gt;object&lt;/code&gt;. If the value of those properties are objects themselves, those objects are not frozen and may be the target of property addition, removal or value re-assignment operations.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The problem isn’t only editing the value, but is also possible add new attributes and delete the current attributes in other branches except for the root, in this branches is like we don’t have anything froze, terrible right?&lt;/p&gt;

&lt;p&gt;To solve this we need to apply the &lt;code&gt;Object.freeze&lt;/code&gt; again in these branches, something like this:&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const accessKeys = {  
  aws: {  
   accessKeyId: 'abc123',  
   secretAccessKey: 'secretValue'  
 },  
 google: 'gogole123'  
}
Object.freeze(accessKeys);  
Object.freeze(accessKeys.aws);
accessKeys.aws.accessKeyId = 'trying to change this value';
console.log(accessKey.aws.accessKeyId); ***//will return 'abc123'* 😃**
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;But you know, if you have many subattributes could be hard to freeze all inner branches, to help us to make it easier we have the method &lt;code&gt;Object.getPropertyNames&lt;/code&gt; available, with this method we get the keys of each branch, and we could navigate inside our object using recursion:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;Now the only task left is to freeze each branch of our tree:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;If you to want to know more about &lt;strong&gt;Javascript&lt;/strong&gt; I recommend these books:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  &lt;strong&gt;You Don’t Know JS Serie by Kyle Simpson (My favourite)&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Eloquent JS by Marijn Haverbeke&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Head First Javascript by Michael Morrison&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;  &lt;strong&gt;Secrets of the JavaScript Ninja by Bear Bibeault and John Resig&lt;/strong&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;a href="https://twitter.com/_rxluz"&gt;Ricardo Luz (@_rxluz) | Twitter&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Thanks for reading! Feel free to hit the recommend if you found this article helpful.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>I wrote an NPM package to prevent infinite recursion in objects</title>
      <dc:creator>Ricardo Luz</dc:creator>
      <pubDate>Tue, 12 Feb 2019 05:33:26 +0000</pubDate>
      <link>https://dev.to/ricardo/i-wrote-an-npm-package-to-prevent-infinite-recursion-in-objects-5422</link>
      <guid>https://dev.to/ricardo/i-wrote-an-npm-package-to-prevent-infinite-recursion-in-objects-5422</guid>
      <description>&lt;p&gt;Sometimes we need to output the data from some objects, but depending on the object structure this simple task could be hard to do, let’s create two small objects to demonstrate this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const a = { hello: 'world' };

const b = { hey: 'hey', hello: a };

a.newProp = b;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the example above we have two objects, a and b, and in the end we connect these objects using the newProp attribute, simple right?&lt;/p&gt;

&lt;p&gt;But what’s happen when we try to output the a object content, let’s say, to a JSON string?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;JSON.stringfy(a)
Uncaught TypeError: Converting circular structure 
to JSON at JSON.stringify (&amp;lt;anonymous&amp;gt;) at &amp;lt;anonymous&amp;gt;:1:6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The problem is we created a connection between a and b, but b was connected before with a from the hello attribute, which makes impossible to generate a JSON structure once this connection is infinite.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2780%2F1%2A_k0QKqdbEEfOOJjRRvsFnw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2780%2F1%2A_k0QKqdbEEfOOJjRRvsFnw.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To solve that we need to create a function that generates a new object without endless recursion, but we also need to keep finite recursion like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const enzo = { 
  name: 'Enzo', 
  otherSon: null, 
}

const validStructure = {
  name: 'John',
  son: enzo,
  otherSon: {
    name: 'Ridlav',
  },
}

enzo.otherSon = validStructure.otherSon

JSON.stringfy(validStructure)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In this example we have the following structure:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;John&lt;/strong&gt; has 2 sons, one &lt;strong&gt;Enzo&lt;/strong&gt; and other &lt;strong&gt;Ridlav&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Enzo&lt;/strong&gt; has one son that is &lt;strong&gt;Ridlav&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The visual representation of this structure will be:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2Ach7t7IIpNKqSWUieSfJUIQ.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F2000%2F1%2Ach7t7IIpNKqSWUieSfJUIQ.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This (strange) structure is a good example of a valid recursion that our function should keep in the final object, to solve that we need to use recursion to remove recursion!&lt;/p&gt;

&lt;p&gt;Let start declaring our function and its parameters:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function preventObjectRecursion(root, list = []) {

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let understand the parameters of this function:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Root:&lt;/strong&gt; Will receive the object that we need to change, but will also receive the attributes of the original object in a second call onwards.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;List:&lt;/strong&gt; Will receive the objects in the path from the root to the current attribute, this will help us to check if this attribute was added before&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The idea is to call this function to each object attribute checking if this attribute was called before in this same path, but to do that first we need to ignore root with other data types (null, function, boolean, strings and numbers), once those types don’t generate recursion:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(!root || typeof root !== 'object') return root
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;After that we need to compare the current root with the objects in the list array, the idea here is to avoid this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F3956%2F1%2A6c2ivDUE0sWMvrKv0_775w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F3956%2F1%2A6c2ivDUE0sWMvrKv0_775w.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In the example above we have a reference to a in the root and another reference to a inside b attribute, to solve that the list parameter will store all the elements in the path (in this case a, b) and check if this element is one of that, if is we avoid this element to being added in our new array:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if(list.length &amp;gt; 0){
  const hasDuplicated = list.some((item: object) =&amp;gt; item === root);
  if(hasDuplicated) return {}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Cool, after this check we need to add the current root in the list path, this will allow analysing this element in the next time that we call our function:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;list.push(root)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Finally, we need to analyse the attributes of the current root element and call this function again to remove any recursion, we’ll the Object.keys to do that:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;return Object.keys(root)
  .reduce((rootClean, key) =&amp;gt; {
    rootClean[key] = preventObjectRecursion(root[key], [...list])
      return rootClean
  }, {})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you want to know more about the reduce method I wrote this article:&lt;br&gt;
&lt;a href="https://medium.com/@_rxluz/2-functional-approach-reduce-c882c68c4cdf" rel="noopener noreferrer"&gt;#2 Functional approach: Reduce … medium.com&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The only difference from the package that I published and the example above is that I used typescript to create the package instead only Javascript, you could check out the result in this Github repo:&lt;br&gt;
&lt;a href="https://github.com/rxluz/prevent-object-recursion" rel="noopener noreferrer"&gt;rxluz/prevent-object-recursion… github.com&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Or simply install from NPM:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm i @rxluz/prevent-object-recursion --save
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Also, please feel free to send to me feedbacks from the comments or opening &lt;a href="https://github.com/rxluz/prevent-object-recursion/issues" rel="noopener noreferrer"&gt;an issue&lt;/a&gt; in Github, this repo needs to increase the number of tests so contributors are welcome!&lt;/p&gt;

&lt;p&gt;And that’s all folks!&lt;br&gt;
&lt;a href="https://i.giphy.com/media/xUPOqo6E1XvWXwlCyQ/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/xUPOqo6E1XvWXwlCyQ/giphy.gif"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>recursion</category>
      <category>object</category>
      <category>json</category>
    </item>
  </channel>
</rss>
