<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Farzad YZ on Medium]]></title>
        <description><![CDATA[Stories by Farzad YZ on Medium]]></description>
        <link>https://medium.com/@Farzad_YZ?source=rss-46be5f3298ab------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*1DhU5oOBXArlDHT5SK5WXw.jpeg</url>
            <title>Stories by Farzad YZ on Medium</title>
            <link>https://medium.com/@Farzad_YZ?source=rss-46be5f3298ab------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:38:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Farzad_YZ/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How To Detect Unique Arrays in JavaScript]]></title>
            <link>https://medium.com/better-programming/detecting-unique-arrays-in-javascript-e4e9a7a87542?source=rss-46be5f3298ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4e9a7a87542</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Farzad YZ]]></dc:creator>
            <pubDate>Wed, 25 Dec 2019 01:42:08 GMT</pubDate>
            <atom:updated>2019-12-29T22:49:27.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sets, multiple types of loops, and more</h4><p>When JavaScript arrays contain primitive values (strings, numbers, undefined, null, booleans, and symbols), there might be cases in which you’re wanting to detect if the array contains any duplicated elements.</p><p>In other words, you would want to determine if elements in the array are unique. There are several approaches you can take to achieve this.</p><p>Let’s take a closer look at our options.</p><h3>Approach 1. Nested Loops</h3><p>In this approach, we will traverse the array, starting from the first element and for each element, we will compare this element to all the other elements to see if there is a match.</p><p>To achieve this, we will use two for loops, nested into each other.</p><pre>function isUnique(arr) {<br>  const len = arr.length;<br>  for (let i = 0; i &lt; len; i++) {<br>    for (let j = 0; j &lt; len; j++) {<br>      // if the elements match, this wouldn&#39;t be a unique array<br>      if (i !== j &amp;&amp; arr[i] === arr[j]) {<br>        return false;<br>      }<br>    }<br>  }<br>  return true;<br>}</pre><p>Although this approach works quite fine with small and semi-small datasets, as the input dataset grows, it gets slower and slower. The slowness of this approach is because of the nested loop.</p><p>Imagine a dataset of a million numbers. In this dataset, in the worst case, our duplicated element could be the last element in the array and, therefore, we would need to compare a million numbers to a million numbers (one million * one million), which is quite slow.</p><ul><li><a href="https://jsfiddle.net/farskid/bquo7k8x/12/">Code</a></li></ul><h3>Approach 2. Single Loop With Cached Values</h3><p>In this approach, instead of comparing each element to every other element, we will keep track of the elements we visit and weren’t a match for a duplicated element.</p><p>In other words, we cache what we traverse and just look them up for the next element to check if we’ve already visited such an element.</p><p>Because of this visited reference, we only need to compare every element in the array to this reference and, therefore, we have to traverse this array only once.</p><pre>function isUnique(arr) {<br>  const seenValues = {}<br><br>  for (let i = 0; i &lt; arr.length; i++) {<br>    // we already saw this element in the array<br>    if (seenValues[arr[i]]) {<br>      return false;<br>    } else {<br>      seenValues[arr[i]] = true<br>    }<br>  }<br><br>  return true;<br>}</pre><p>In the worst case of a million numbers in a dataset, our duplicated element will be the last element but in this approach, we only compare one million times. This approach is significantly faster than approach 1.</p><ul><li><a href="https://jsfiddle.net/farskid/zky1mdug/18/">Code</a></li></ul><h3>Approach 3. Using ES6 Set</h3><p>When ES6 came around, we were introduced to a new data structure in JavaScript called Sets.</p><p>Sets are a collection of elements that are unique by definition, meaning that, if you try to insert a duplicated element into a set, it won&#39;t have any effects.</p><p>Due to Sets being a collection of unique elements by definition, there is a technique to convert arrays into sets which, in turn, results in a unique collection of items in that array, now stored in the set.</p><p>Then, a reverse operation will be used to convert that Set back to an array. In a sense, you could say that Set is used as an intermediate data structure to remove duplicate elements from the array.</p><p>Array -&gt; Set -&gt; Array</p><pre>// convert an array to a set and convert back<br>function getUniqueArray(arr) {<br>  return [...new Set(arr)]<br>}<br><br>function isUnique(arr) {<br>  return getUniqueArray(arr).length === arr.length<br>}</pre><p>In this approach, if the number of elements inside the unique array (converted back from Set) is the same as the input array length, it means this array already contained unique values and no duplicated values were removed from it to alter the length.</p><p>Note: You don’t need to convert a Set back to an array if you just want to check for uniqueness. You can skip this part of the operation totally by checking Set.prototype.size.</p><pre>// convert an array to a set<br>function arrayToSet(arr) {<br>  return new Set(arr)<br>}<br><br>function isUnique(arr) {<br>  return arrayToSet(arr).size === arr.length<br>}</pre><h3>Performance Comparison</h3><p>Using any of these three approaches interchangeably is fine as long as your dataset is relatively small. For larger datasets, you need to keep an eye on performance of these approaches and how many operations they could execute in a limited duration.</p><p>The short answer for performance comparison between these three is:</p><p>Approach 2 &gt; Approach 3 &gt; Approach 1.</p><p>Approach 2 (using single loop with cached values) is significantly faster than the rest. Between approach 3 (Set) and approach 1 (nested loops), approach 3 is also much faster.</p><p>To have a better understanding of these performance comparisons, take a look at this benchmark:</p><p><a href="https://esbench.com/bench/5e0273c1170166009e5470f7">ESBench</a></p><h3>Side Note for Whoever Is Curious</h3><ul><li>Approach 1 (using nested loops) is of quadratic complexity, meaning that it will result in O(n2) time complexity.</li><li>Approach 2 (using single loop and cached values) is of linear complexity, meaning that it will result in O(n) time complexity.</li><li>For approach 3, I don’t have a strong opinion as I’m not fully aware of how Sets are being implemented in JavaScript engines under the hood.</li></ul><h3>Conclusion for the Impatient</h3><p>Do not pre-optimize for a problem you don’t have. Performance optimizations make sense only when you have a large dataset to bring slowness to the surface.</p><p>For relatively small datasets, it won’t matter which approach you take as all will behave fast enough. For larger datasets, always lean towards using approach 2 as benchmarks show it’s significantly faster.</p><figure><img alt="Performance comparison of 3 approaches for detecting unique arrays in Javascript" src="https://cdn-images-1.medium.com/max/880/0*i6hudSinohkEHBiL.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4e9a7a87542" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/detecting-unique-arrays-in-javascript-e4e9a7a87542">How To Detect Unique Arrays in JavaScript</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useBackButton hook to handle back button behavior in React Native]]></title>
            <link>https://medium.com/@Farzad_YZ/usebackbutton-hook-to-handle-back-button-behavior-in-react-native-d7666226d644?source=rss-46be5f3298ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7666226d644</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Farzad YZ]]></dc:creator>
            <pubDate>Mon, 12 Aug 2019 00:14:36 GMT</pubDate>
            <atom:updated>2019-11-25T20:59:19.104Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://reactjs.org/docs/hooks-intro.html">React hooks</a> help with carrying stateful logic and keeping their lifecycle separate from the view layer lifecycle. They’ve been around since React v16.8 and since people have been avoiding class components in favor of hooks.</p><p>One of the somewhat interesting aspects of hooks is their flexibility in terms of composition and abstraction. If a code snippet using different <a href="https://reactjs.org/docs/hooks-reference.html">built-in hooks</a> is handling a part of logic that is separate and independent from other parts, it can be abstracted away as a <a href="https://reactjs.org/docs/hooks-custom.html"><strong>Custom Hook</strong></a>.</p><h3><strong>useBackButton custom hook</strong></h3><p>To handle the behavior of hardware back button in Android and tvOS devices using React Native, there is <a href="https://facebook.github.io/react-native/docs/backhandler.html"><em>BackHandler</em></a> API that can assist in overriding the default behavior or patching it.</p><p>BackHandler takes an event-driven approach to offer an API, meaning that to subscribe to back button presses, you’ll need to register an event listener.</p><pre>import { BackHandler } from &quot;react-native&quot;;</pre><pre>function backButtonHandler() {}</pre><pre>BackHandler.addEventListener(&quot;hardwareBackPress&quot;, backButtonHandler);</pre><p>and of course, to de-register this subscription, you’ll need to use removeListener, the same way we do so handling DOM events.</p><pre>backButtonHandler.removeEventListener(&quot;hardwareBackPress&quot;, backButtonHandler);</pre><h3><strong>use Hooks to utilize BackHandler</strong></h3><p>Subscriptions are side effects! therefore, we can use useEffectbuilt-in hook to execute them. It’s important to notice that useEffectrequires us to return a function to remove the subscription once React is willing to clean up! Cleanups are usual when the component is being unmounted or one of the dependencies of the useEffecthook change, so React needs to clean up previous subscriptions of that hook and re-execute it!</p><p><a href="https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup">Read more about subscriptions and cleanups in <em>useEffect</em></a></p><pre>function backButtonHandler() {}<br><br>function MyComponent() {<br>  useEffect(() =&gt; {<br>    BackHandler.addEventListener(&quot;hardwareBackPress&quot;, backButtonHandler);<br><br>    return () =&gt; {<br>      BackHandler.removeEventListener(&quot;hardwareBackPress&quot;, backButtonHandler);<br>    };<br>  }, [backButtonHandler]);<br><br>  return &lt;View&gt;...&lt;/View&gt;;<br>}</pre><h3><strong>useBackButton is born!</strong></h3><p>while the above code snippet works perfectly, copy-pasting it into all the screens might sound frustrating to some of us (we’re freaks after all)! To help to remove our frustrations, React offers a way to build your custom hook.</p><pre>/* ComponentA */<br>function backButtonHandlerForA() {}<br>function ComponentA() {<br>  // Frustration begins!<br>  useEffect(() =&gt; {<br>    BackHandler.addEventListener(&quot;hardwareBackPress&quot;, backButtonHandlerForA);<br><br>    return () =&gt; {<br>      BackHandler.removeEventListener(<br>        &quot;hardwareBackPress&quot;,<br>        backButtonHandlerForA<br>      );<br>    };<br>  }, [backButtonHandlerForA]);<br><br>  return &lt;ViewA /&gt;;<br>}<br><br>/* ComponentB */<br>function backButtonHandlerForB() {}<br>function ComponentB() {<br>  // Frustration begins!<br>  useEffect(() =&gt; {<br>    BackHandler.addEventListener(&quot;hardwareBackPress&quot;, backButtonHandlerForB);<br><br>    return () =&gt; {<br>      BackHandler.removeEventListener(<br>        &quot;hardwareBackPress&quot;,<br>        backButtonHandlerForB<br>      );<br>    };<br>  }, [backButtonHandlerForB]);<br><br>  return &lt;ViewB /&gt;;<br>}</pre><p>A custom hook is just an abstraction to share the same logic between components and hooks, the same way we do this between functions in a regular programming.</p><p>Components are functions. Hooks are functions as well. You get the idea, right?!</p><p>In cases of <em>ComponentA </em>and <em>ComponentB</em> samples above, registration, removal and hook implementation are the same. it’s just the handlers that can be different per component. So our custom hook needs to provide those common parts and only accept the changing part (handler per component) as an incoming argument.</p><pre>/* useBackButton */<br>function useBackButton(handler) {<br>  // Frustration isolated! Yay! 🎉<br>  useEffect(() =&gt; {<br>    BackHandler.addEventListener(&quot;hardwareBackPress&quot;, handler);<br><br>    return () =&gt; {<br>      BackHandler.removeEventListener(<br>        &quot;hardwareBackPress&quot;,<br>        handler<br>      );<br>    };<br>  }, [handler]);<br>}<br><br>/* ComponentA */<br>function backButtonHandlerForA() {}<br>function ComponentA() {<br>  // utilize custom hook<br>  useBackButtton(backButtonHandlerForA);<br>  return &lt;ViewA /&gt;;<br>}<br><br>/* ComponentB */<br>function backButtonHandlerForB() {}<br>function ComponentB() {<br>  // utilize custom hook<br>  useBackButtton(backButtonHandlerForB);<br><br>  return &lt;ViewB /&gt;;<br>}</pre><h3><strong>Recap</strong></h3><p>If you intend to share a common logic between components and built-in hooks, you can abstract that away by building your custom hook. Make sure to read the impressively detailed docs of Hooks and <strong>Rules of Hooks</strong> from the official docs.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7666226d644" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing Higher-Order Components with Enzyme and Jest]]></title>
            <link>https://medium.com/@Farzad_YZ/unit-testing-higher-order-components-using-enzyme-b9bfad668a42?source=rss-46be5f3298ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9bfad668a42</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[enzyme]]></category>
            <category><![CDATA[higher-order-components]]></category>
            <dc:creator><![CDATA[Farzad YZ]]></dc:creator>
            <pubDate>Fri, 03 Nov 2017 01:45:22 GMT</pubDate>
            <atom:updated>2018-07-08T15:47:31.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajHwi9cueCSsLeB32weQrQ.jpeg" /></figure><p>Not all the components you write for your React application can be divided into Stateful and Stateless (dumb) categories. There is a 3rd advanced type of component in React called a <em>higher-order component</em>. A <a href="https://reactjs.org/docs/higher-order-components.html">higher-order component</a> is a function that takes a component as an argument and returns another component. Check out <a href="https://medium.com/@Farzad_YZ/handle-loadings-in-react-by-using-higher-order-components-2ee8de9c3deb">my other article</a> to see how higher-order components are used in the real world.</p><h3>Creating a HOC with Tests</h3><p>We’ll be using <a href="https://github.com/airbnb/enzyme">Enzyme</a> and <a href="https://facebook.github.io/jest/">Jest</a>, but these concepts apply to any testing library.</p><p>One of the common HOCs I write for every project of mine is called withConditional<strong>. </strong>Its purpose is to render a component if and only if the condition passes, otherwise just return null.</p><pre>import React from &#39;react&#39;;</pre><pre>const withConditional = Component =&gt;</pre><pre>  function withConditionalComponent({ condition, ...props }) {</pre><pre>    if (condition) {</pre><pre>      return <em>&lt;Component</em> {...props} <em>/&gt;</em>;</pre><pre>    }</pre><pre>    return null;</pre><pre>};</pre><pre>export default withConditional;</pre><p>As you can see, when the condition passed to the HOC evaluates to true, it returns the component, otherwise it returns null<em>.</em></p><p>So how can you unit test the HOC? There are surprisingly minimal articles talking about unit testing these components, and I had a hard time figuring out the proper way. Recently the solution clicked!</p><h3>Solution</h3><p>To properly test these badass components, you just need to know that they are <strong>simple functions</strong> and that’s all!</p><p>withConditional is used in the following manner</p><pre>const ConditionalComponent = withConditional(MyComponent);</pre><pre>class HelloWorld extends React.Component {</pre><pre>  render() {</pre><pre>    return (&lt;ConditionalComponent condition={3 &gt; 4} /&gt;);</pre><pre>  }</pre><pre>}</pre><p>So, we should use the exact same concept to unit test them as well.</p><p>The important thing to take into account here is to test the component for all states. For instance, if our HOC can handle two different states, depending on the condition passed to it, then we MUST account for both states in the tests.</p><h4>When condition <strong>passes</strong>:</h4><pre>it(<br>  &#39;should render the component only when the condition passes&#39;<br>  , () =&gt; {</pre><pre>  const ConditionalComponent = withConditional(Component);</pre><pre>  const wrapper = shallow(<br>    <em>&lt;ConditionalComponent</em> condition={true} <em>/&gt;<br>  </em>);</pre><pre>  expect(wrapper.html()).not.toBe(null);</pre><pre>});</pre><h4>When condition fails:</h4><pre>it(<br>  &#39;should return null when the condition fails&#39;<br>  , () =&gt; {</pre><pre>const ConditionalComponent = withConditional(Component);</pre><pre>const wrapper = shallow(<br>    <em>&lt;ConditionalComponent</em> condition={false} <em>/&gt;<br>  </em>);</pre><pre>expect(wrapper.html()).toBe(null);</pre><pre>});</pre><p>Have fun and test it up!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9bfad668a42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Ways to clone objects in JavaScript]]></title>
            <link>https://medium.com/@Farzad_YZ/3-ways-to-clone-objects-in-javascript-f752d148054d?source=rss-46be5f3298ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/f752d148054d</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[objects]]></category>
            <category><![CDATA[clones]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Farzad YZ]]></dc:creator>
            <pubDate>Sun, 01 Oct 2017 18:17:29 GMT</pubDate>
            <atom:updated>2019-07-02T07:02:01.440Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AbdeAwXHGpIoBuJvLJ38lQ.jpeg" /><figcaption>Clone!</figcaption></figure><p>Cloning an object in JavaScript a task that is almost always used in any project, to clone everything from simple objects to the most complicated ones.</p><p>As it may seem simple for not seasoned JavaScript developers, it actually has some pitfalls that would hurt you in the bones if you didn’t know the proper way to do it.</p><h3>Talk is cheap, show me the code</h3><p>The first way that could cross a developer’s mind is to deeply iterate through a source object’s properties and copy them one by one on the target object. It may seem good at the beginning, but it is not a performance-friendly solution potential bottlenecks come when working with large or deep objects.</p><p><strong>1: Deep copy using iteration</strong></p><p><em>Note: To copy deeply, we need to recursively detect if the value is yet another object (object literal in this case, functions and arrays will be treated normally) or not.</em></p><pre>// source: <a href="https://github.com/jashkenas/underscore/blob/master/underscore.js#L1320">https://github.com/jashkenas/underscore/blob/master/underscore.js#L1320</a><br>function isObject(obj) {<br>  var type = typeof obj;<br>  return type === &#39;function&#39; || type === &#39;object&#39; &amp;&amp; !!obj;<br>};</pre><pre>function iterationCopy(src) {<br>  let target = {};<br>  for (let prop in src) {<br>    if (src.hasOwnProperty(prop)) {<br>      // if the value is a nested object, recursively copy all it&#39;s properties<br>      if (isObject(src[prop])) {<br>        target[prop] = iterationCopy(src[prop]);<br>      } else {<br>        target[prop] = src[prop];<br>      }<br>    }<br>  }<br>  return target;<br>}</pre><pre>const source = {a:1, b:2, c:3};<br>const target = iterationCopy(source);<br>console.log(target); // {a:1, b:2, c:3}</pre><pre>// Check if clones it and not changing it<br>source.a = &#39;a&#39;;<br>console.log(source.a); // &#39;a&#39;<br>console.log(target.a); // 1</pre><pre><br>// Nested example!<br>const x = {a: 1, b: {c: 1}};<br>const y = iterationCopy(x);</pre><pre>x.b.c = 2;<br>console.log(y.b.c); // still &quot;1&quot;</pre><p>So as you see, it’s working!</p><p>Now let’s cut the chase to the second solution which is indeed more elegant but, more limited to use.</p><p><strong>2: Converting to JSON and back</strong></p><pre>function jsonCopy(src) {<br>  return JSON.parse(JSON.stringify(src));<br>}</pre><pre>const source = {a:1, b:2, c:3};<br>const target = jsonCopy(source);<br>console.log(target); // {a:1, b:2, c:3}</pre><pre>// Check if clones it and not changing it<br>source.a = &#39;a&#39;;<br>console.log(source.a); // &#39;a&#39;<br>console.log(target.a); // 1</pre><blockquote>Note: Be careful about using this method as your source object <strong>must</strong> be JSON safe. So it may need some sort of exception handling to keep it safe in cases in which the source object is not convertible to JSON.</blockquote><p><strong>3: Using </strong><strong>Object.assign</strong></p><blockquote><strong>Update: </strong>This method has a flaw that it only does a shallow copy. It means that nested properties are still going to be copied by reference. Be careful about it.</blockquote><p>This way is the best and the safest way I personally consume in my projects. It’s leveraging a built-in static method on the Object object and is handled and provided by the language. So use this one!</p><pre>function bestCopyEver(src) {<br>  return Object.assign({}, src);<br>}</pre><pre>const source = {a:1, b:2, c:3};<br>const target = bestCopyEver(source);<br>console.log(target); // {a:1, b:2, c:3}</pre><pre>// Check if clones it and not changing it<br>source.a = &#39;a&#39;;<br>console.log(source.a); // &#39;a&#39;<br>console.log(target.a); // 1</pre><h3>Conclusion</h3><p>Every framework and library, such as Lodash and Underscore, have a way to support cloning objects. Almost all of them used a more complex version of iterationCopy<em> </em>before ES6 was introduced. On ES6+ environments, there is language support for Object.assign, so try to use the most out of it. As a rule of thumb, always try to use the 3rd solution and avoid the JSON solution.</p><p>Keep calm and clone objects without any hesitation :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f752d148054d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle loadings in React by using Higher Order Components]]></title>
            <link>https://medium.com/@Farzad_YZ/handle-loadings-in-react-by-using-higher-order-components-2ee8de9c3deb?source=rss-46be5f3298ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ee8de9c3deb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[higher-order-components]]></category>
            <dc:creator><![CDATA[Farzad YZ]]></dc:creator>
            <pubDate>Mon, 18 Sep 2017 17:13:12 GMT</pubDate>
            <atom:updated>2018-01-12T17:09:53.395Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7Fb6uAwTDrWhrf5XCt6Fw.jpeg" /><figcaption>Higher Order Components in React</figcaption></figure><p>Before you read this article, <a href="https://facebook.github.io/react/docs/higher-order-components.html">read React’s official document on HOCs</a> if you haven’t read it yet.</p><p>Pretty much in any React application, you call an API to fetch some data and use them to render some content in your application.<br>Since UI components need to show some kind of progress bar, loading indicator, etc to tell users that data is being fetched, it may be cumbersome to implement loading logic in every single component and to pass a loading property from your redux store or your local state to child components.<br>In order to make this situation easier, React proposes <strong>Higher Order Components</strong> to shield away repetitive code snippets and be generic as much as you can.</p><h3>Higher Order Component (HOC)</h3><p>A higher order component or HOC as you may face a lot surfing through the web, is a function that accepts your component as an argument and returns a new function that adds some feature to the component. A sharp example of it is the <strong>Connect</strong> HOC in <a href="https://github.com/reactjs/react-redux">React-Redux</a> library that makes your store model available as props to your components and containers.</p><h3>Loading a List</h3><p>For instance, assume we are fetching a list of a developer’s repositories from Github using its open API. We tend to handle list loading so that our clients wouldn’t panic when the API is taking so much time to respond.</p><p>A basic <em>List </em>component can be written as:</p><pre>import React from &#39;react&#39;;</pre><pre>const List = props =&gt; {<br>  const { repos } = props;<br>  <br>  if (!repos) return null;<br>  if (!repos.length) return (<em>&lt;</em>p<em>&gt;</em>No repos, sorry<em>&lt;/</em>p<em>&gt;</em>)</pre><pre>  return (<br>    <em>&lt;</em>ul<em>&gt;<br>      </em>{<br>        repos.map(repo =&gt; {<br>          return (<br>            <em>&lt;</em>li key={repo.id}<em>&gt;</em>{repo.full_name}<em>&lt;/</em>li<em>&gt;<br>          </em>)<br>         })<br>       }<br>    <em>&lt;/</em>ul<em>&gt;<br>  </em>)<br>}</pre><pre>export default List;</pre><p>Now, let’s write the HOC to handle loadings:</p><pre>import React from &#39;react&#39;;</pre><pre>function WithLoading(Component) {<br>  return function WihLoadingComponent({ isLoading, ...props }) {<br>    if (!isLoading) return (&lt;Component {...props} /&gt;);<br>    return (&lt;p&gt;Be Hold, fetching data may take some time :)&lt;/p&gt;);<br>  }<br>}</pre><pre>export default WithLoading;</pre><p>Now in your container such as App.js , you could easily pass loading logic to WithLoading without being worried about it in your List .</p><h3>Put it into Action</h3><pre>import React from &#39;react&#39;;<br>import List from &#39;./List.js&#39;;<br>import WithLoading from &#39;./WithLoading.js&#39;;</pre><pre>const ListWithLoading = WithLoading(List);</pre><pre>class App extends React.Component {<br>  state = {<br>    loading: false,<br>    repos: null<br>  }</pre><pre>  componentDidMount() {<br>    this.setState({ loading: true });<br>    fetch(`https://api.github.com/users/farskid/repos`)<br>      .then(json =&gt; json.json())<br>      .then(repos =&gt; {<br>        this.setState({ loading: false, repos: repos });<br>      });<br>  }</pre><pre>render() {<br>    return (<br>      &lt;ListWithLoading isLoading={this.state.loading} repos={this.state.repos} /&gt;<br>    )<br>  }</pre><pre>}</pre><h3>Wrap it Up</h3><p>we did see that using an HOC really makes it easier to deal with loadings in UI and fades out all those manual if-else statements in every single component that is rendering a data from the API.</p><p>Have Fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ee8de9c3deb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage and Promisify async actions in javascript]]></title>
            <link>https://medium.com/@Farzad_YZ/manage-and-promisify-async-actions-in-javascript-e2a36cbac534?source=rss-46be5f3298ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2a36cbac534</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[cashback]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Farzad YZ]]></dc:creator>
            <pubDate>Sun, 22 Jan 2017 10:15:56 GMT</pubDate>
            <atom:updated>2017-01-22T10:15:56.522Z</atom:updated>
            <content:encoded><![CDATA[<p>javascript is different from other languages. Programmers from other languages once entering the javascript era might get confused easily but the action is not true on the reverse side. One of the easy to get yet hard to implement and maintain task in Javascript is to perform an <strong>async</strong> task.</p><p>To asynchronously run a task in Javascript, Developers have 3 different options.<br>1. <strong>Callbacks</strong> (ES5)<br>2. <strong>Promises</strong> (ES6)<br>3. <strong>Async / Await</strong> (ES7: still draft)</p><p>In this article we are going to cover the first 2 options yet leaving the third one to the audience, probably lots of snippets and great articles could be found about it around the internet.</p><h3>Asynchronous Task</h3><p>An asynchronous task is a task that’s not going to return value as soon as it’s called, the timestamp between calling the async task and returning the value is unknown and dependant to many factors.</p><h3>Callback</h3><p>To control the returning value from our async task and working with it, our first and the hardest to maintain and chain, would be callbacks. Callbacks are first class functions passed to the async function as an argument.<br>Let’s assume our async function is just a <em>setTimeout</em> that returns a random integer.</p><pre>function myAsyncTask() {<br>  setTimeout(function() {<br>   return Math.random()<br>  }, 1000)<br>}</pre><p>And also assume that we are going to control the returned value by multiplying by 2.</p><pre>function controller(input) {</pre><pre>  alert(input)<br>}</pre><p>To pass controller to the async function, it should accept an argument:</p><pre>function myAsyncTask(callback) {</pre><pre>  setTimeout(function() {</pre><pre>    callback(Math.random())</pre><pre>  }, 1000)<br>}</pre><p>Now we pass the controller to the async function to see what happens!</p><pre>myAsyncTask(controller)</pre><p>This will alert double of the random input after 1 seconds. Give it a try!</p><p>As you see, callbacks are nice BUT, what if we wanna do multiple async tasks altogether? what if we wanna share code snippets and function in nested callback calls? Nested callbacks are typically HELL. I mean it. In fact they are so hard to maintain that in Node JS, since all tasks are asynchronous, the tasks should be called nested and you’ll simply end up with multiple (easily up to 5 steps) nested callbacks inside each other.<br>This problem led the dev community into requesting other tools to manage these kind of functions and the tool was called <strong>PROMISE.</strong></p><h3>Promise</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4qCR2qvJ-WjuoZhckzpbw.png" /><figcaption>Javascript promise infographic</figcaption></figure><p>Promise came to make dev lives easier. promises are often hard to understand. Once I saw above infographic about a weather forecast example and how it can be converted to promise concept (<a href="http://andyshora.com/promises-angularjs-explained-as-cartoon.html"><em>originally from Andy Shora Blog</em></a>), I finally grasped the concept.</p><blockquote>Promises are like, hey code snippet, promise me to do this async task, if your returned value fulfills this condition, resolve the value else reject it.</blockquote><p>Every promise has a resolve and reject function that are relatively success and error of task. Promises are like try-catch` blocks. You could chain promises infinite times but pass the errors down to the single bottom catch.</p><p>The resolve function is used inside a .thenmethod and the reject in .catch<br>Let’s rewrite our fake async task in promise manner!</p><pre>function myAsyncTask() {<br>  return new Promise(function(resolve, reject) {<br>   setTimeout(function() {<br>    var rand = Math.random()<br>    if (rand &gt; 0.5) resolve(rand)<br>    else reject(rand)<br>   }, 1000)<br>  })<br> }</pre><pre>function resolveController(input) {<br>  alert(&#39;Value greater than 0.5 is :&#39; + input)<br>}<br>function rejectController(input) {<br>  alert(&#39;Value less that 0.5 is : &#39; + input)<br>}</pre><p>Now since the resolve function is resolveController and reject function is rejectController, use <strong>resolveController</strong> inside <em>.then and </em><strong>rejectController</strong><em> </em>inside<em> .catch .</em></p><pre>myAsyncTask().then(resolveController).catch(rejectController)</pre><p>The code is now better read, better understood and much easier to chain and maintain.</p><h3>Last Attack</h3><p>As appeared in title of this article, <strong>promisify</strong> is the process of converting a callback based procedure into promise. It’s actually simple and useful for some reasons.<br>1. It’s luxury :-P<br>2. It’s modern javascript and more up-to-dated<br>3.It’s better to read and look at<br>4. Many async tasks such as reading and writing to fileSystem, Ajax request, Connecting to and querying on database,… are present inside a real world javascript application and you gotta get out from the callback hell ASAP</p><p>So how do we convert a callback hell to a promise paradise? It’s freakingly easy. Just parallel convert success callbacks and error callbacks into resolve and reject respectively. Consider below jQuery ajax request:</p><pre>function getDataFromServer(url, success, fail) {<br>  return $.getJson(url, success, fail)<br>}</pre><pre>function getUsersByCallback() {<br>  return getDataFromServer(&#39;<a href="https://myrestapi.com/users&#39;">https://myrestapi.com/users&#39;</a>,function(response) {<br>   console.log(&#39;Yesss, I got users&#39;)<br>  },function(error) {<br>   console.error(&#39;Bummer, could not get users right now&#39;)<br>  })<br> }</pre><p>Once converted into promise, would look like:</p><pre>function getDataFromServer(url) {<br>  return new Promise(function(resolve, reject) {<br>   $.getJson(url, function(response)      {resolve(response)},function(error) {reject(error)})<br>  })<br> }</pre><pre> function getUsersByPromise() {<br> getDataFromServer(&#39;<a href="https://myrestapi.com/users&#39;).then(function(response)">https://myrestapi.com/users&#39;).then(function(response)</a> {<br>   console.log(&#39;Yesss, I got users&#39;)<br>  }).catch((error) {<br>   console.error(&#39;Bummer, could not get users right now&#39;)<br>  })<br> }</pre><p>That easy!!!!</p><h3><strong>Conclusion</strong></h3><p>Async tasks are everywhere even outside of javascript and every language provides stable methods and tools to deal with them. In javascript callbacks, promises and async/awaits are available as solutions. As you saw, async/await is still a draft but has been implemented in recent versions of Babel transpiler so you could give it a try but don’t get used to it to much as it could vanish like in seconds.<br>Promisify your async tasks with the technique discussed in the article and you’re good to go further that working inside a callback hell.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2a36cbac534" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-Domain Iframe-parent communication]]></title>
            <link>https://medium.com/@Farzad_YZ/cross-domain-iframe-parent-communication-403912fff692?source=rss-46be5f3298ab------2</link>
            <guid isPermaLink="false">https://medium.com/p/403912fff692</guid>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[iframe]]></category>
            <dc:creator><![CDATA[Farzad YZ]]></dc:creator>
            <pubDate>Wed, 28 Dec 2016 16:14:15 GMT</pubDate>
            <atom:updated>2019-04-02T21:01:49.603Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Fair warning: This solution worked for the certain use case explained in the article back in 2016, the same date this very article was published. It might not work right now!</strong></p><p>There are many cases iframe would be a good solution to use. Although they are kind of dead to HTML and not a lot of developers use it, It could come up to you as a solution to a complicated problem some day.</p><p>Knowing a way to communicate through an iframe to parent is such a valuable and time saver. Maybe iframe could tell it’s parents when it’s content is ready or engage user interactions inside the iframe with the parent to react properly.</p><p>Some days ago at my company, we had a Wordpress website that loaded an iframe for choosing a plan to buy virtual machines as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Npna_TbF8ChgAroSVkyu_Q.png" /><figcaption>An iframe included inside Wordpress to choose VM plans</figcaption></figure><p>I was assigned a task to do something challenging on this element. The company intended to open a URL on click of the orange button, BUT because the button was inside the iframe, that couldn’t be managed easily.</p><p>First thing I tried to was to use postMessage to send a message from iframe to its parent. I came up with this code:</p><p>&lt;iframe src=&quot;Path/To/Html&quot;&gt;&lt;button id=&quot;my-btn&quot;&gt;Start&lt;/button&gt;&lt;/iframe&gt;</p><pre>document.getElementById(&#39;my-btn&#39;).addEventListener(&#39;click&#39;, handleButtonClick, false);</pre><pre>function handleButtonClick(e) {</pre><pre>  window.parent.postMessage(&#39;iframe_message&#39;)<br>}</pre><p>And also listen to the message on the parent window:</p><pre>window.addEventListener(&#39;iframe_message&#39;, function() {</pre><pre>  window.open(&#39;some url&#39;, &#39;_blank&#39;)<br>}, false);</pre><p>It was perfect! worked like a charm. It passed some minutes until I figured out the actual problem. This only worked for same-domain iframes. Apparently, cross-domain iframes don’t post the message to the parent properly.</p><p>I dogged the web a lot and found a really interesting inspiration on a dark edge of StackOverflow. Although It did not help me, It fixed me in the right direction. The solution was to use custom events.</p><p>So I refactored the solution to:</p><pre>document.getElementById(&#39;my-btn&#39;).addEventListener(&#39;click&#39;, handleButtonClick, false);</pre><pre>var myEvent = new CustomEvent(&#39;my_event&#39;, { detail: {url: &#39;some url&#39;} })</pre><pre>function handleButtonClick(e) {</pre><pre>window.parent.dispatchEvent(myEvent)<br>}</pre><p>And listen to it on the parent of course:</p><pre>window.addEventListener(&#39;iframe_message&#39;, function(e) {</pre><pre>var url = e.detail.url</pre><pre>window.open(url, &#39;_blank&#39;)<br>}, false);</pre><p>It was amazing as I could easily pass custom data from iframe to the parent window.</p><h3>Conclusion:</h3><p>Dealing with iframes is Hard. It’s not intended to be used unless there is no other way to do it.</p><p>If you’re using a same-domain iframe, you’re in heaven. You could easily control iframe’s content and also communicate with its parent through postMessage.</p><p>But you’re in Hell when it gets cross-domain. You could only use CustomEvent and dispatchEvent on the iframe and listen to it on the parent window. In this case, try to modularize your communication protocol and pass custom data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=403912fff692" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>