<?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 Jason Lim on Medium]]></title>
        <description><![CDATA[Stories by Jason Lim on Medium]]></description>
        <link>https://medium.com/@porzingod?source=rss-f82ae4c63dcf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jTJylOmC2VsA2PGf.</url>
            <title>Stories by Jason Lim on Medium</title>
            <link>https://medium.com/@porzingod?source=rss-f82ae4c63dcf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:20:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@porzingod/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[Agile Development Intro Journal pt. 2]]></title>
            <link>https://medium.com/@porzingod/agile-development-intro-pt-2-9f109c1cf639?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f109c1cf639</guid>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Mon, 20 Aug 2018 00:57:10 GMT</pubDate>
            <atom:updated>2018-08-20T00:57:45.837Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week I journaled about what it was like working in an agile environment for the first time. This week we concluded the 2 week sprint and came full circle on the agile process.</p><p>Throughout the week, I continued to work on my task of migrating some Rails views to React. With a lot of the groundwork laid in the first week for this task, this week involved a lot more writing in React and optimizing the interaction between Rails and React.</p><p>One of the issues that needed immediate fixing was a bug with Turbolinks, a Ruby gem, that was causing React to render components multiple times when navigating with history. This was added to a bug list and needed to be fixed before the end of the week before demos. We used YouTrack for bug logging as well. For this issue, it turned out there are known issues with using Turbolinks and React Router because they both handle the back and forward buttons. I pair programmed with the lead developer to try out different ways of fixing the issue while both using Turbolinks and React Router. In the end, the best fix was to disable Turbolinks on every React view.</p><p>As it became closer to Friday, any new code being pushed needed to be reviewed and approved for merging to the demo branch. I remember the importance of having a fresh set of eyes look over my code so it was nice to have my code reviewed and approved as well as review other developer’s code.</p><p>Friday morning we had a meeting to discuss what new things have been added to the demo branch and what things were kept out for the time being and why. After our meeting concluded, we presented the updated demo to everyone else. Each developer talked about the new changes they made and walked through the application while doing so.</p><p>After the demo presentation, the developers had another meeting where we had a “retrospective”. We finalized what tasks were completed this sprint on YouTrack and moved unfinished tasks to next week’s sprint. Then we discussed what things went well during the sprint, what things could have gone better, and what things could be improved. One thing I felt went well was that the backend and frontend were better set up for future migrating. The API I worked on will become more fleshed out in time and React was set up now with routing and greater compartmentalization for better structure.</p><p>It was great learning to work on a larger team, something I hadn’t had the opportunity in my previous coding experiences. I highly valued the chance to have my code reviewed and to see other people’s code as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f109c1cf639" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Agile Development Intro Journal]]></title>
            <link>https://medium.com/@porzingod/agile-development-intro-89f5550ee4d8?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/89f5550ee4d8</guid>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Mon, 13 Aug 2018 00:03:30 GMT</pubDate>
            <atom:updated>2018-08-20T00:57:30.745Z</atom:updated>
            <content:encoded><![CDATA[<p>Currently I’m partaking in a trial period for an internship which means I’ve been quickly introduced to the codebase and the team’s agile development process. Having only worked on solo and pair projects in the past, it’s been a refreshing experience so far. The team I am currently working with has 2 week development cycles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*qo8EmZcLS5xh8ZgBBMFftw.jpeg" /></figure><p>On this team, the start of a cycle meant looking back at the task log and seeing which tasks were completed and which would need to be moved to the new cycle’s task log. We’re using a site called YouTrack to log what needs to be done, what is being worked on, what is awaiting verification and what is verified/completed. For the cycle I got assigned with migrating a Rails view page to React. The team has a naming system for the tasks which you also name your git branch as to keep consistency.</p><p>Having used a similar product in Trello, I started by filling out a few cards with general, smaller goals to migrate the Rails view to React. What I realized throughout the week were side objectives that needed to be accomplished to help me finish the overall task of migrating the view. These were added to their own cards and to my task board. It was a great way to visualize what I had completed and still needed to finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iwd3tdkT0RauS9Oo86ooJQ.png" /><figcaption>YouTrack</figcaption></figure><p>Next I was introduced to using GitLab and their deployment/merge process. The repository was set up with automated testing so any git commits that did not pass all tests were not pushed. It was important to run the testing suite before committing to ensure my commits were pushed. Once the commits are passing, I had to submit a merge request to have my code reviewed. I was left with comments at various files with suggestions. Gitlab made it easy to see and reply to comments if there was any confusion. After I had made changes to my code to satisfy the comments I received, I submitted a new merge request which then got approved. I was still working off my branch but now the code I wrote was part of a larger branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*E3e3UzJlb4fpk3aCkTS19A.jpeg" /><figcaption>GitLab</figcaption></figure><p>Each day we the team met for stand ups where we let everyone know the things we worked on, what we’re currently working on and any blockers we were facing. My main blockers throughout the week were just knowing where to find the code I thought I might need. Receiving help for my blockers after stand ups was great because it set me up well with the information I needed for the rest of the day.</p><p>What’s left for this cycle is to review everything we’ve worked on through the 2 weeks. I’m hoping to get everything done and passing all tests in preparation for the review.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89f5550ee4d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hoisting “var” vs. “let”]]></title>
            <link>https://medium.com/@porzingod/hoisting-var-vs-let-c040075889d5?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c040075889d5</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Mon, 06 Aug 2018 03:58:33 GMT</pubDate>
            <atom:updated>2018-08-06T04:04:04.119Z</atom:updated>
            <content:encoded><![CDATA[<p>When I started learning Javascript, I was told why not to use <strong>var</strong>. I was told, that because <strong>let</strong> and <strong>const</strong> were introduced in ES2015, <strong>var </strong>was no longer useful. <strong>let </strong>was the mutable variable declarator and <strong>const </strong>was the immutable variable declarator. The difference was easy enough to grasp and I only used <strong>let</strong> and <strong>const</strong> going forward.</p><p>However the two hoist differently.</p><pre>var foo = 1;</pre><pre>function bar(){<br>  if(!foo) {<br>    var foo = 10;<br>  }<br>  alert(foo);<br>};</pre><p>Will this alert 1 or 10?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*r8uVjxRHWUr1NMWbU-IoKw.png" /></figure><p>If you said 1, you were wrong like me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*Ad9KqXKfmRdQ8ETusC6rUw.png" /></figure><p>I totally didn’t understand what was going on coming from my world of only using <strong>let</strong> and <strong>const</strong>. I tried out the same lines of code but with <strong>let</strong> instead of <strong>var</strong> and as expected, the window alerted 1 not 10. But why, was 10 being alerted with <strong>var</strong>?</p><p>A quick google search led me to the answer that it has to do with the way <strong>var</strong> and <strong>let</strong> are initialized. With hoisting, when variables are declared, their reference is moved to the top of the scope. It would look something like below.</p><pre>var foo = undefined; // hoisted foo reference<br>var bar = undefined; // hoisted bar reference<br>foo = 1;</pre><pre>bar = function(){<br>  var foo = undefined; // hoisted foo reference<br>  if(!foo) {<br>    foo = 10;<br>  }<br>  alert(foo);<br>};</pre><p><strong>let </strong>and<strong> const </strong>have block scoping so they won’t be hoisted and referenced like <strong>var</strong> until they are initialized. So in the previous code sample, <strong>let</strong> is declared in the global block scope and becomes available within function bar().</p><p>The way variable declaration works with <strong>var</strong>, also applies to <strong>function</strong> and <strong>function* </strong>while <strong>let</strong>, <strong>const</strong> and <strong>class</strong> behave similarly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Aan7VmfDYnzJdn-j2LKRyQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c040075889d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Timer component using setInterval() + clearInterval()]]></title>
            <link>https://medium.com/@porzingod/timer-component-using-setinterval-clearinterval-18df5e15e2c9?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/18df5e15e2c9</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Mon, 30 Jul 2018 02:23:46 GMT</pubDate>
            <atom:updated>2018-07-30T02:31:06.076Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Journaling a recent bug fix and code refactor</strong></h4><h4><strong>TLDR:</strong> Set a variable for <strong>setInterval() </strong>so you can <strong>clearInterval() </strong>later.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*0Q-26DvaTuFYxz9Y9NuG4A.jpeg" /><figcaption>YOU KNOW WHAT TO DO!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*0SV6RykMhOvMNSGGgX6zxQ.gif" /></figure><p>Recently, as part of a coding assignment I built a timer using React. The specific instructions aside, it was clear what the main functionality of the Timer component should be. It would need a way to increment the time values and update the component continually.</p><p>For those unfamiliar, in Javascript, this can be achieved using a method called <strong>setInterval()</strong>. It will take a callback and repeatedly call it at a fixed time delay between each call.</p><p>In the first iteration of the assignment, I decided my code would benefit from the use of a helper function to create <strong>setInterval()</strong> methods for each time unit seen above. Minutes, seconds and centiseconds (hundredths of a second). Each of these units were being kept track of individually in the class’ state and updated at various intervals indicated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*aqplaQGI6tBe9Z7rz96QBQ.png" /></figure><p>I was happy with how readable the code was and the code reuse. However, after some observation of the timer in effect, I noticed an undesirable effect. A task of the assignment wanted a split to highlight the clicked split, reset the timer to the split’s time, and remove all splits below. You can see the effect in the above gif.</p><p>When the split was removed, the timer would reset correctly but the intervals had not changed so sometimes you could see the time go up a second at something like 50 centiseconds or 36 centiseconds, etc.</p><p>I identified the issue could be solved by resetting the <strong>setInterval() </strong>functions. Also although it initially made sense to increment each time unit independently, it was the main cause of the seconds unit incrementing when it clearly shouldn’t. Also in order to stop/reset the <strong>setInterval() </strong>I would need the<strong> clearInterval() </strong>method as well. But to use <strong>clearInterval()</strong> I have to store the <strong>setInterval()</strong> method as a variable accessible later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*0weR0QuCBIEqDMdhDFEGPA.png" /></figure><p>The helper function was removed and the minutes and seconds time units will update dependent on a mix of the other time units. I also saved the <strong>setInterval()</strong> method to a local variable <strong>intervals</strong> which can later be accessed within the Timer component class through <strong>this.intervals</strong>.</p><p>The initial version used many if/else statements to confirm the conditionals, but through the use of ES6 destructuring, nested ternary operators and arrow functions, the conditions of updating a time unit were better detailed individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*qUY7GhA86psS-qk5Pg5kzA.png" /></figure><p>Finally I added the <strong>clearInterval() </strong>method followed immediately by calling the starter function that contained the <strong>setInterval().</strong> Because <strong>setInterval() </strong>functions go into effect immediately, it is good practice to save it to a variable. In my earlier code it would be impossible to <strong>clearInterval()</strong> on these lines.</p><pre>let hunds = this.timeIntervalSetter(&quot;hundredths&quot;, 100, 10)<br>clearInterval(this.hunds)<br>// also no effect because hunds is not where setInterval() is called but timeIntervalSetter() is.</pre><pre>this.timeIntervalSetter(&quot;hundredths&quot;, 100, 10)<br>clearInterval(this.timeIntervalSetter) <br>// no effect because timeIntervalSetter is not the specific reference</pre><p>Thanks for reading! I am open to receiving any feedback regarding my code and thought process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18df5e15e2c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fibonacci and Memoization]]></title>
            <link>https://medium.com/@porzingod/fibonacci-and-memoization-e99f765b97f6?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e99f765b97f6</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Mon, 23 Jul 2018 01:46:08 GMT</pubDate>
            <atom:updated>2018-07-23T23:27:49.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*SBRPHl4yMEQpAfNWoTDbYg.gif" /><figcaption>source: mathisfun.com</figcaption></figure><p>During a recent coding test I was asked to write a function that returns the Fibonacci number at given index. For those unfamiliar, the Fibonacci sequence is a series of numbers starting with 0 and 1. The following numbers are found by adding up the last two numbers. From index 0 to 9, the series is 0, 1, 1, 2, 3, <strong>5</strong>, 8, 13, 21, 34. I was able to do this successfully through an iterative method.</p><pre>// iterative solution - O(n)</pre><pre>function fib(n) {<br>  let fibo = [0, 1]<br>  for(let i = 2; i &lt;= n; i ++) {<br>    let res = fibo[i - 1] + fibo[i - 2]<br>    fibo.push(res)<br>  }<br>  return fibo[fibo.length - 1]<br>}</pre><p>Next, I was asked if I could implement this function in a recursive fashion. I sat there for a few minutes trying to figure out what my base case would be and how I would recurse toward the base case. However, I could not solve this.</p><p>Following the coding test I immediately went to searching for how to write a Fibonacci function recursively. The answer I found at multiple sources looked like this.</p><pre>function fib(n) {<br>  if (n &lt; 2) {<br>    return n<br>  }<br>  return fib(n - 1) + fib(n - 2)<br>}</pre><p>Now I knew the answer to this particular question if asked. The function itself is easy to remember. However, I wanted to understand this implementation better.</p><p>Recursion in general can be a bit hard to wrap your head around. To aid in analyzing this function I diagramed it below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*0929NnIABCqCDg6yfJEZ4A.png" /></figure><p>From this visualization you can see the recursive implementation reaches the correct answer through the addition of 1s (and 0s). It’s good to understand recursion by visualizing the call stack. In the case of<strong> fib(4)</strong>, function <strong>fib </strong>is called 9 times. For a computer keeping track of the <strong>fib </strong>function 9 times is not a huge burden, so this is not a big deal.</p><p>It will become a big deal as the entered index increases. Let’s look at the visualization of <strong>fib(5).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*uc4P0Yg_2vvusGEdsxVLBg.png" /></figure><p>Incrementing the index by 1 raised the number of <strong>fib</strong> calls to 15. You can imagine what problem this will raise once we want to find the Fibonacci number at higher indexes. Its complexity in Big O notation is O(2^n).</p><pre>// recursive solution - O(2^n)</pre><pre>function fib(n) {<br>  if (n &lt; 2) {<br>    return n<br>  }<br>  return fib(n - 1) + fib(n - 2)<br>}</pre><p>The same thing I noticed while creating the visualization was the repeated <strong>fib(n) </strong>calls. When fib(5) recurses down to fib(4) and fib(3), fib(4) will recurse down again to fib(3) and fib(2). I thought, if there is a way to store the return value of fib(3) then the other fib(3) can just refer to the stored value and not recurse. What I wanted to achieve is called <strong>memoization.</strong></p><h3>Memoization</h3><blockquote>In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Memoization">https://en.wikipedia.org/wiki/Memoization</a></blockquote><pre>// generic memoization function</pre><pre>function memoize(fn) {<br>  let cache = {}<br>  return function(...args) {<br>    if (cache[args]) {<br>      return cache[args]<br>    }<br>    const res = fn.apply(this, args)<br>    cache[args] = res<br>    return res<br>  }<br>}</pre><pre>// apply memoization to fib function</pre><pre>fib = memoize(fib)</pre><p>The above memoization function can be used to memoize any function. As you can see there is an object called cache which we will be using to store our return values. It will check if the cache has a reference to the argument and if not then it will the apply the function to the argument and then store the return value. This will reduce the number of recursive calls and the visualization should look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*wq_mEtPiR__02-ZJavKmNA.png" /><figcaption>O(n) + O(1) = O(n)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e99f765b97f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cleaner Code With ES6 Destructuring]]></title>
            <link>https://medium.com/@porzingod/cleaner-code-with-es6-destructuring-24d7e1199b8a?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/24d7e1199b8a</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Sun, 15 Jul 2018 23:02:11 GMT</pubDate>
            <atom:updated>2018-07-15T23:04:02.257Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*dMjHpEuZ80zbM06dDXlBHg.jpeg" /></figure><p>When I began my coding journey, Javascript was the first language I learned. I was then introduced to Ruby and honestly, until that point I had been struggling understanding the syntax and concepts in Javascript. Ruby helped a lot because with my limited knowledge, the language was so much more readable. I eventually became more comfortable with both languages and lately have been diving deeper in Javascript to be better equipped for web development.</p><p>This week I attended the Javascript NYC meetup where Donavon West, currently Developer Relations at American Express, gave a talk on Clean Code vs Dirty Code. I especially learned greatly from his use of destructuring to write cleaner code because I knew my code had suffered from un-destructured use of objects.</p><p>As most of us may be familiar with objects in Javascript, we know this syntax of returning the value of an object’s key.</p><pre>let myObject = {<br>  &quot;foo&quot;: &quot;bar&quot;,<br>  &quot;fiz&quot;: &quot;baz&quot;<br>}</pre><pre>myObject.foo // &quot;bar&quot;<br>myObject.fiz // &quot;baz&quot;</pre><p>We use objects all the time when working with fetched data or writing object oriented Javascript. Also most of us if using libraries like React have used destructuring as well.</p><p>Below is an example JSON object from an API. In my old project, I would have most likely passed the entire object to my React state. I probably told myself I might need the other data in the future. I didn’t. If I wanted to create a schedule using information like this, I likely only need the season, away team, home team and time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*Kj1FiYDG2NrOerFO0021Ig.png" /><figcaption>example JSON from <a href="https://api.fantasydata.net/v3/nba/">api.fantasydata.net</a></figcaption></figure><pre>fetch(&#39;www.mynbadata.com/api&#39;)<br>.then(res =&gt; res.json())<br>.then(res =&gt; this.setState({nbaData: res}))</pre><p>One level up from this step I knew I didn’t want to type this.state constantly so I destructured state.</p><pre>const {nbaData} = this.state</pre><p>If we only destructure this, one level deep then we likely end up typing nbaData constantly.</p><pre>render() {<br>  &lt;div&gt;{nbaData.AwayTeam} @ {nbaData.HomeTeam} - {nbaData.DateTime}<br>  on {nbaData.Channel}&lt;/div&gt;<br>}</pre><p>The JSON data being returned has easy to read keys. Why don’t I make my code easier to read as well by destructuring one more level up.</p><pre>const {nbaData: { AwayTeam, HomeTeam, DataTime, Channel }} = this.state</pre><pre>render() {<br>  &lt;div&gt;{ AwayTeam } @ { HomeTeam } - { DateTime } on { Channel }<br>  &lt;/div&gt;<br>}</pre><p>Now the code has become much more readable. Going back to the original setState method, maybe it would be better for me to determine what data I will store at the very first point in time.</p><pre>fetch(&#39;www.mynbadata.com/api&#39;)<br>.then(res =&gt; res.json())<br>.then(res =&gt; {<br>  let nbaData = res.map(element =&gt; { AwayTeam, HomeTeam, DateTime, <br>  Channel })<br>  this.setState({ nbaData })<br>)</pre><p>I’m sure every individual and team’s coding practices will have slight variations but I found destructuring, a good and easy first step into making my code cleaner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*Z3GCWy0wXCeD0lTYJYrTHg.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24d7e1199b8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Redux Middlewares]]></title>
            <link>https://medium.com/@porzingod/writing-redux-middlewares-6c172e2bd5d7?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c172e2bd5d7</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Sun, 08 Jul 2018 22:12:44 GMT</pubDate>
            <atom:updated>2018-07-15T23:08:17.347Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-Q6mKafmPSsh2OsMCsSE-A.jpeg" /></figure><p>This week I wanted to understand the Redux cycle a bit better, and in particular wanted to look at the middleware part of Redux.</p><p>A middleware is essentially a function, that are chained with other middleware. They occur in sequence after an action is dispatched and before it reaches the reducer. When an action is dispatched, the dispatch function passes the action through all the middlewares, then passes it to all appropriate reducers. One thing to note is, that middleware should not be dependent on other middleware. The action should pass through all middlewares and return untouched.</p><p>As the action goes through a chain of applied middlewares, known as the ‘middleware stack’, only the middlewares that pertain to the action will apply. There are middleware that happen for all actions such as redux-logger and only on some actions such as redux-thunk.</p><p>All middleware are built using below template.</p><pre>function middleware = ({ dispatch, getState }) =&gt; next =&gt; action =&gt; {}</pre><p>Through Redux’s applyMiddleware function, the middleware we write here will be passed store’s dispatch and getState methods. It will return a function with the next method which will return a function with action parameter. Calling dispatch(action) will send the action back through the middlewares as if it was a normally dispatched action. Calling next(action) will pass the action to the next middleware.</p><p>Below is an example of a logger middleware that will console.log the store’s current state, the action that was dispatched, and then store’s next state. This middleware will apply to every action since it has no conditionals for the action being passed. With the logger middleware, there isn’t a need for the dispatch method so I only passed the getState method as the first parameter. Some styling was added by grouping the three console.logs and added color to each.</p><pre>// src/middlewares/logger.js</pre><pre>export default ({ getState }) =&gt; next =&gt; action =&gt; {<br>  console.group(&#39;logger&#39;)<br>  console.log(&#39;%c prev state: &#39;, &#39;color: grey&#39;, getState())<br>  console.log(&#39;%c action&#39;, &#39;color: blue&#39;, action)<br>  next(action)<br>  console.log(&#39;%c next state: &#39;, &#39;color: green&#39;, getState())<br>  console.groupEnd()<br>};</pre><p>Below is an example of a async middleware that has a conditional and will only apply to asynchronous operations. With this middleware, we don’t need the getState method so I only passed store’s dispatch method. We know that an asynchronous fetch request will return a promise that we can call .then() on. So if the action.payload.then returns a function, we create a new action that is the response of the promise and dispatch the new action, sending the action with new payload back through the middleware stack. When the new action hits the async middleware again, this time there will be no .then method available since it will not be a promise and will be passed along the middleware stack.</p><pre>// src/middlewares/async.js</pre><pre>export default ({ dispatch }) =&gt; next =&gt; action =&gt; {<br>  // check to see if action has a promise on it&#39;s payload property<br>  if (!action.payload || !action.payload.then) {<br>    // if it doesn&#39;t, send action to next middleware(s)<br>    return next(action);<br>  }<br>  // it does. Wait to resolve<br>  action.payload.then(response =&gt; {<br>    // create a new action with the received data<br>    // now the payload has data as its payload instead of a promise<br>    const newAction = {...action, payload: response};<br>    // dispatch the new action to run through middlewares again<br>    dispatch(newAction)<br>  });<br>};</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c172e2bd5d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React + Redux testing using Enzyme]]></title>
            <link>https://medium.com/@porzingod/react-redux-testing-using-enzyme-608758f7ace6?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/608758f7ace6</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Fri, 06 Jul 2018 20:27:19 GMT</pubDate>
            <atom:updated>2018-07-15T23:50:31.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*TOs8wsc_8Z6gIUrnWqwVVw.png" /></figure><p>Through my experience building solo projects, I realized it was a luxury to see changes occur after every hot reload of the localhost. This week I wanted to learn how to test in the React environment.</p><p>I decided to use <a href="https://github.com/airbnb/enzyme">enzyme</a> for testing because it made testing components easier. Enzyme is an open source library maintained by Airbnb used for testing in React. Look and compare the two tests below that do the same thing.</p><pre>import React from &#39;react&#39;;<br>import { shallow } from &#39;enzyme&#39;;<br>import App from &#39;components/App&#39;<br>import CommentBox from &#39;components/CommentBox&#39;;</pre><pre>// without enzyme<br>it (&quot;shows a comment box&quot;, () =&gt; {<br>  const div = document.createElement(&#39;div&#39;);<br>  ReactDOM.render(&lt;App/&gt;, div);<br>  expect(div.innerHTML).toContain(&#39;Comment Box&#39;);<br>  ReactDOM.unmountComponentAtNode(div);<br>});</pre><pre>// with enzyme<br>it (&quot;shows a comment box&quot;, () =&gt; {<br>  let wrapper = shallow(&lt;App /&gt;);<br>  expect(wrapper.find(CommentBox).length).toEqual(1);<br>});</pre><p>Aside from there being fewer lines, enzyme makes it much easier to maintain the tests going forward. In the case of the test without enzyme, we can of course change the expectation to look something like this to be more specific to the CommentBox.</p><pre>expect(div.getElementsByClassName(&quot;Comment Box&quot;).length).toBe(1);</pre><p>However, both are not scalable. If we change the innerHTML of CommentBox our test will break. But with the enzyme test, all we care for is that the CommentBox component resides inside the App component. Whether CommentBox contains “Comment Box” as a class or text or neither will not affect the enzyme test.</p><p>You might be wondering what this line is.</p><pre>import { shallow } from ‘enzyme’</pre><p>Enzyme provides three higher order functions — render, shallow and mount — that accept a component you want to test.</p><p>With the <strong>render</strong> method, the component is rendered to a static HTML so that its HTML contents can be analyzed.</p><p>With the <strong>shallow</strong> method, the component is rendered without rendering any child components. This is great for testing out a single component without any leaked effects from child components. In <strong>shallow </strong>render, the component has access to all React lifecycle methods such as componentDidMount and componentDidUpdate.</p><p>Lastly, with <strong>mount</strong> method, the component is rendered as well as its child components. A great use for mount is integration testing, when you want to perform and test multiple actions that may affect various components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*nBey0I0_4hEG7t8o1r1-vg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=608758f7ace6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ternary Operators]]></title>
            <link>https://medium.com/@porzingod/ternary-operators-49ae3d42abf?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/49ae3d42abf</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Tue, 10 Apr 2018 04:05:16 GMT</pubDate>
            <atom:updated>2018-04-10T04:07:44.071Z</atom:updated>
            <content:encoded><![CDATA[<p>Hopefully a full look at one of the best conditional operators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*XRGkuUld6SfrEyCnjbREMg.jpeg" /><figcaption><strong>return toiletPaper.placedCorrect ? “You are an exemplary human being.” : “You are barbarian scum.”</strong></figcaption></figure><p>A ternary operator is another way of writing a conditional operator. One reason to use a ternary operator over a standard if/else statement is its compact syntax. Using our ternary operator in the picture caption above as an example, if you were to write this as a normal if/else statement it would look like this.</p><pre>if ( toiletPaper.placedCorrect ) { <br>  return &quot;You are an exemplary human being.&quot;<br>} else {<br>  return &quot;You are barbarian scum.&quot;<br>}</pre><p>Although this is simple to read it can become cumbersome to write out. It’s also possible if you’re like me you’ll forget to close your if conditional in a parenthesis. Much shorter to write is the ternary version seen above in the caption.</p><pre>return toiletPaper.placedCorrect ? &quot;You are an exemplary human being.&quot; : &quot;You are barbarian scum.&quot;</pre><p>Pseudo code way of thinking about ternary operators can be</p><pre>// if condition is true ? do this : else do that</pre><p>Along with compact syntax, the code above is a single line and much easier to read. Also, despite the compact syntax, ternary operators are not limited to simple if/else statements. It is possible to write an if statement nested inside of another if statement. It would look like the code below.</p><pre>return animal.isCat ? ( animal.isDog ? &quot;It&#39;s a catdog&quot; : &quot;Not a catdog&quot; ) : &quot;Not a catdog&quot;</pre><pre>// &#39;It&#39;s a catdog&#39;</pre><p>We know it’s possible to do a nested if/else statement using multiple ternary statements. However, isn’t a ternary statement only an if and and else? Wrong. Ternary operators can also be used to write else if statements as well. Like other if/else if/else statements, each conditional will be checked in sequential order.</p><pre>return 2 &gt; 3 ? &quot;two is greater than three&quot; : 2 === 3 ? &quot;two equals three&quot; : 2 &lt; 3 ? &quot;two is less than three&quot; : &quot;somehow 2 &lt; 3 is false&quot;</pre><pre>// &#39;two is less than three&#39;</pre><p>Written a little easier to read.</p><pre>return 2 &gt; 3 ? &quot;two is greater than three&quot;<br>     : 2 === 3 ? &quot;two equals three&quot;<br>     : 2 &lt; 3 ? &quot;two is less than three&quot;<br>     : &quot;somehow 2 &lt; 3 is false&quot;</pre><pre>// &#39;two is less than three&#39;</pre><p>In pseudo code.</p><pre>// if condition is true ? do this <br>// : else if is this condition true ? do this<br>// ...<br>// : (more else ifs) ? do this<br>// ...<br>// : else do this</pre><p>There are some rules with ternary operators, however. You cannot write any loops inside any of its expressions and it doesn’t like when there are other parenthesis inside it.. However, you can use map or other array iterators. Just make sure to use commas for each line.</p><pre>2 &gt; 3 ? (<br>  &#39;HOW?&#39;<br>  ) : (<br>  array = [1, 2, 3, 4, 5],<br>  array.map( x =&gt; x + 1 )<br>)</pre><pre>// [2, 3, 4, 5, 6]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*qj2b790mbKDoaennEvGKnw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49ae3d42abf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WeakMaps Are Secretly Delicate]]></title>
            <link>https://medium.com/@porzingod/weakmaps-are-secretly-delicate-b56e332beca?source=rss-f82ae4c63dcf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b56e332beca</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jason Lim]]></dc:creator>
            <pubDate>Tue, 20 Mar 2018 13:58:17 GMT</pubDate>
            <atom:updated>2018-03-20T13:58:17.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*nXWdXhUZ4FTEkrT-eVlGDQ.gif" /></figure><p>Ruby had a simple way to differentiate between public and private methods. You simply wrote code after the <strong>private</strong> keyword. In Javascript however, it is not as simple. Actually there is no built in method yet to create private methods. I discovered there are a number of workarounds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*l0U089F-EW-okm-CAxT-cA.png" /></figure><p>In this example, a new Dog object is constructed with <strong>this._name </strong>attribute. In Javascript, the underscore character is treated like any other character. It doesn’t explicitly come built in with special attributes. Often times the<strong> ._method</strong> syntax is used to distinguish private methods. However, because the underscore is simply another character in Javascript, the naming of methods using <strong>._method</strong> only works based on trust that the user will not call the “private” method. Also in this convention we can still use <strong>._name</strong> to modify the instance. Let’s say we had a sign up page where the user must enter their information into fields, some of which we do not want changed in the future. There are no built in systems in place to prevent the altering of the user’s username or any other data associated with the or others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*_yzktHBLOTL5JVIaUpozPw.png" /></figure><p>This example is a bit better. The use of <strong>Object.defineProperty()</strong> defaults to make an object immutable. The variables <em>privateData</em> and <em>privateId</em> are only accessible through the IIFE and objects once created are stored immutably in the <em>privateData</em> object. However, this means that even if our object is removed, it persists in the <em>privateData</em> object. Also we are using the <strong>._id</strong> method which we know is not truly private. This approach works to prevent the altering of data but has some artifacts of Javascript that make it not completely private and leaves in existence other objects.</p><h4><strong>Enter WeakMaps.</strong></h4><p>WeakMaps are a type of object introduced in ES6 which hold a collection of key value pairs. Unique to WeakMaps and Maps, also introduced in ES6, are the option to hold an object as a key, including functions since functions are also objects. However, unlike Maps which can hold any datatype in its keys, WeakMaps can only hold an object as its key.</p><p>As the name suggests the key that is being referenced in a WeakMap object is weakly referenced. This means any change or removal of the key will mitigate the reference established. This feature is beneficial in creating more secure, private methods that are only relevant as long as the instance calling the method is relevant. WeakMaps were designed this way to prevent memory leaks and to help with garbage collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*s2F4n5BnrrnrVFiroQsLqA.png" /></figure><p>In this code we have created a WeakMap object in the IIFE of a new Dog. WeakMaps can only be accessed and modified via the <strong>.set(), .get(), delete() and .has()</strong> methods. By creating a new Dog object and setting the weakmap variable’s key to “this” (new Dog instance), key is now unique to the instance. Only accessible through the IIFE, the only way for us to call back to the weakmap variable that holds our dog’s name is to set a getName() method to the Dog class objects. By using a WeakMap, we did not have to use any underscore methods, which as we know are only respectfully private.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*LO1GJ1_2qimjuLZfFNTXGg.png" /></figure><p>Alternatively we can set the WeakMap getter method as .getData() and append key calls to it. In these examples when we set the weakmap with “this”, it is treated more as a check to see if what the WeakMap references is still the same. The key/value collections pushed through can be accessed like other objects. Thus, if we use .getData() instead of .getName() + .getBreed() we can write a method that returns all information or specified to return certain information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*CerobdinCLHm0l9bsVrykw.png" /></figure><p>Lastly, as mentioned earlier, a WeakMap is only accessible as long as the referencing key has remained unchanged. Our Dog instance <em>max</em> belongs to the Dog class. However when we edit <em>max</em> to become just an object <em>max</em> is no longer the same object as before. So when <em>max.getData()</em> is called, “this” in <em>weakmap.get(this)</em> is no longer the same <em>max as before</em>. Our weakmap for <em>max</em> is now gone. Unless a new Dog instance of <em>max</em> is created .getData() will no longer be able to be called for <em>max</em>. However by then the new Dog instance of <em>max</em> is still not our old <em>max</em>.</p><p>Be good to your WeakMaps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*2BaEIMFm6yzVyT8-KClzjA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b56e332beca" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>