<?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 Reuben Nahouraii on Medium]]></title>
        <description><![CDATA[Stories by Reuben Nahouraii on Medium]]></description>
        <link>https://medium.com/@reubennahouraii?source=rss-ad95e1d4696e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_-ZV_HCItAhlJKrzYAQyPg.png</url>
            <title>Stories by Reuben Nahouraii on Medium</title>
            <link>https://medium.com/@reubennahouraii?source=rss-ad95e1d4696e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 15 Nov 2026 19:53:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reubennahouraii/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[The difference between var, const, and let in Javascript is…]]></title>
            <link>https://codeburst.io/the-difference-between-var-const-and-let-in-javascript-is-845f8a6ae928?source=rss-ad95e1d4696e------2</link>
            <guid isPermaLink="false">https://medium.com/p/845f8a6ae928</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Reuben Nahouraii]]></dc:creator>
            <pubDate>Tue, 19 Sep 2017 00:12:14 GMT</pubDate>
            <atom:updated>2017-09-19T12:43:49.787Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gawAqZ3XJyg6aTmtbj3G6A.jpeg" /></figure><p>I was recently chatting with a friend while we were on a hike, and we started to discuss the differences between <strong>var</strong>, <strong>const</strong>, and <strong>let</strong> in Javascript. We talked about the what, how, and when to use each. And from that discussion, this post was born…</p><p>First, a little history. In the dark ages of Javascript (pre-ES6, that is) there was only the <strong>var</strong>. If you wanted to declare a variable, all you had to do was pound on the keys v-a-r and you were done. There were no other decisions that had to be made. Life was easy… Then came along ES6 with all of its fancy options, meh. Life was never to be simple again (cue sad music).</p><p>Okay, enough with the melodrama ;-)</p><p>The introduction of <strong>const</strong> and <strong>let</strong> to es6 is a very welcome and needed update. <strong>Const</strong> and <strong>let</strong> introduced block scope to Javascript (an idea that is prevalent in many other languages, including C and C++). Let’s see how it works.</p><pre><strong>let </strong>status = &#39;awake&#39;;<br><br>{ // a new block -- yawn, let&#39;s take a little nap<br><br>  <strong>let </strong>status = &#39;napping&#39;;<br>  console.log(status); // napping<br><br>} // time to get back to work -- end nap<br><br>console.log(status); // awake -- as expected</pre><p>So, because <strong>let</strong> is block-scoped (blocks being defined by the code between the opening and closing curly braces), the status is still ‘awake’ outside of the block. The inner status of ‘napping’ doesn’t leak out of the block into the outer scope. (<strong>Const</strong>, like <strong>let</strong>, is also block-scoped.)</p><p>Now, let’s look at <strong>var</strong>. <strong>Var</strong> is function-scoped.</p><pre><strong>var </strong>status = &#39;awake&#39;;<br><br>{ // a new block -- yawn, let&#39;s take a little nap<br><br>  <strong>var </strong>status = &#39;napping&#39;;<br>  console.log(status); // napping<br><br>} // time to get back to work -- end nap<br><br>console.log(status); // napping -- yikes</pre><p>As you can see, <strong>var</strong> doesn’t respect the block. The napping that was declared inside of the block, clobbered the declaration made outside of the block. As mentioned earlier, this happened because <strong>var</strong> is function-scoped as opposed to block-scoped.</p><p>Takeaway — if you don’t want to get caught napping at work, use <strong>let</strong> or <strong>const</strong>.</p><p>Another example where this might cost you some time debugging is in order…</p><pre><strong>let </strong>count = 5;<br>// 20 lines of code<br><br><strong>for</strong>(<strong>let </strong>count = 0; count &lt; 15; count++) {<br>  // do stuff<br>}<br><br>// 10 lines of code<br>console.log(count); // 5 -- as expected</pre><p>Using <strong>let</strong>, things are as they should be. Now it’s <strong>var</strong>’s turn…</p><pre><strong>var </strong>count = 5;<br>// 20 lines of code<br><br><strong>for</strong>(<strong>var </strong>count = 0; count &lt; 15; count++) {<br>  // do stuff<br>}<br><br>// 10 lines of code<br>console.log(count); // 15 -- smh</pre><p>I hope that by this time, if you didn’t understand before, you understand block-scoping vs functional-scoping with regards to <strong>let</strong>, <strong>const</strong>, and <strong>var</strong>. (I know that I haven’t touched on <strong>const</strong> at all, yet, and that is because it acts exactly like <strong>let</strong> when it comes to scope.)</p><p>Your wait is over… The time has come to talk <strong>const</strong>. The <strong>const</strong> keyword creates a declaration that cannot be reassigned.</p><pre><strong>const </strong>reassignMeAtYourOwnPeril = &#39;Klaatu Barada Nikto&#39;;<br>reassignMeAtYourOwnPeril = &#39;Klaatu Verada Nec...&#39;;<br>// error -- the world is safe<br>console.log(reassignMeAtYourOwnPeril); // never runs</pre><p>In the above example trying to reassign the <strong>const</strong> declaration creates an error and the console.log code will never be executed. Let’s see what happens when we run the same code using <strong>var</strong> or <strong>let</strong> (both <strong>var</strong> and <strong>let</strong> have the same behavior with regards to reassignment).</p><pre><strong>let </strong>reassignMeAtYourOwnPeril = &#39;Klaatu Barada Nikto&#39;;<br>reassignMeAtYourOwnPeril = &#39;Klaatu Verada Nec...&#39;;<br>console.log(reassignMeAtYourOwnPeril); // Klaatu Verada Nec...<br>// code executes and the dead rise -- oops...</pre><p>As you can see, a variable declared with <strong>let</strong>, similarly to <strong>var</strong>, can be reassigned. (Possibly having some dire consequences…)</p><p>Alright, now I’m about to ask you to look at a code sample and make a decision. Adjust your browser window accordingly so that you don’t accidently see the answer that is going to be just underneath the code sample… I want to go over a point of possible confusion regarding a <strong>const</strong> declaration. Look at the code sample below and decide whether or not an error will occur.</p><pre><strong>const </strong>booksOfTheDead = [&#39;Vol 0&#39;, &#39;Vol 1&#39;, &#39;Vol 2&#39;];<br>booksOfTheDead[0] = &#39;Necronomicon&#39;;  // Will this cause an error?</pre><blockquote>If you’re finding this content helpful in some way, don’t be shy, give me a clap :-) Thanks!</blockquote><p>If you decided that an error would not occur, then you decided right! The <strong>const</strong> declaration has to do with reassignment. When we change an item in an array, reassignment is not occurring. Rather, we are making a change to the underly data structure (an array in this case).</p><p>Here is a similar code sample that will result in an error…</p><pre><strong>const </strong>booksOfTheDead = [&#39;Vol 0&#39;, &#39;Vol 1&#39;, &#39;Vol 2&#39;];<br>booksOfTheDead = []; // Error, can&#39;t reassign</pre><p>See the difference? In this last example, we are trying to reassign booksOfTheDead to an empty array, which is not going to be allowed when using a <strong>const</strong> declaration.</p><p>Lastly, I would like to share the rule that I follow when deciding whether I should use <strong>var</strong>, <strong>const</strong>, or <strong>let</strong>. First, I look at <strong>const</strong>. If I’m not intending to do any reassignment, then <strong>const</strong> is a clear winner. (You should use <strong>const</strong> whenever you can.) Next, I look to <strong>let</strong>. And I basically use <strong>let</strong> in every situation where I don’t use <strong>const</strong>, ie, there will be a reassignment. My last choice is <strong>var</strong>. If for some reason, neither <strong>const</strong> nor <strong>let</strong> will provide me with the needed behavior, then fine, <strong>var</strong> it is…</p><p>A final note on <strong>const</strong> — using <strong>const</strong> is beneficial because it is making your intention explicit. When another programmer comes along, perhaps even yourself, weeks — months — years later, and they need to make some change to the codebase, it is very beneficial for them to know the declarations that are being reassigned vs those that should definitely <em>not</em> be reassigned. It can save a lot time lost, and frustration had, by debugging. Do the world a solid, use <strong>const</strong> if you can.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=845f8a6ae928" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/the-difference-between-var-const-and-let-in-javascript-is-845f8a6ae928">The difference between var, const, and let in Javascript is…</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Tree Problems.]]></title>
            <link>https://codeburst.io/binary-tree-problems-100e37eea0a3?source=rss-ad95e1d4696e------2</link>
            <guid isPermaLink="false">https://medium.com/p/100e37eea0a3</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Reuben Nahouraii]]></dc:creator>
            <pubDate>Thu, 24 Aug 2017 08:13:15 GMT</pubDate>
            <atom:updated>2017-08-28T17:03:50.382Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bI1iFsqWHUHyg1-IGU_eeQ.jpeg" /></figure><p>Hi, whoever may be reading this from the future, I hope that your journey into the wonderful world of software engineering has been awesome! Mine started a few years back, and I must say, it has definitely been one of the best experiences, to date, of my life :-)</p><p>Today, I went to an interview-prep meetup at the way-too-early time, 8:30am. The subject was Binary Trees, and we were given a few problems to solve. (Quick shout-out to Jack Wong for hosting the meetup!) Well, I solved the problems, and I thought, why not write a blog post explaining the problems, and then, the solutions that I came up with.</p><blockquote>** Disclaimer — I am not under the impression, nor do I claim, that my solutions are the most efficient. The solutions that I came up with are just that… solutions that I came up with o_O</blockquote><h3>The Problems:</h3><p>1. Build a Binary Tree (note — not a Binary Search Tree)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*MBZJw38JaT_aalZxLl_6XA.png" /></figure><p>2. Find all paths to leaves (ie, 2–3–9, 2–3–4, 2–8–7, 2–8–1)</p><p>3. Find the longest sequential path</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*IBqXhtluJjPVwHnruXCG4Q.png" /></figure><p>4. Invert the Binary Tree from the earlier problem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*ZTF_Q07nsqnx0GjFn-eiiQ.png" /></figure><p>Give it a go! After you’ve come up with your own solutions, or at a minimum, put some thought into how you would solve these problems, check out my solutions.</p><h3>The Solutions:</h3><p>1. Build a Binary Tree (note — not a Binary Search Tree)</p><pre><strong>const </strong>Node = <strong>function</strong>(value) {<br>  <strong>this</strong>.value = value;<br>  <strong>this</strong>.right = <strong>null</strong>;<br>  <strong>this</strong>.left = <strong>null</strong>;<br>};<br><br>Node.prototype.insert = <strong>function</strong>(value) {<br>  <br>  <strong>let </strong>queue = [<strong>this</strong>],<br>      node;<br>  <strong>while</strong>(queue.length) {<br>    node = queue.shift();<br>    <strong>if</strong>(node.left &amp;&amp; node.right)<br>      queue.push(node.left, node.right);<br>    <strong>else<br>      break</strong>;<br>  }<br><br>  <strong>if</strong>(!node.left)<br>    node.left = <strong>new </strong>Node(value);<br>  <strong>else<br>    </strong>node.right = <strong>new </strong>Node(value);<br>};<br><br><strong>let </strong>root = <strong>new </strong>Node(2);<br>[3,8,9,4,7,1].forEach(value =&gt; root.insert(value));</pre><p>A few notes on the above code…</p><ul><li>I used a queue to populate the tree because a queue allows me to traverse level by level looking for leaves. Using this strategy, the tree will populate level by level from left to right.</li><li>Putting all of the values in an array and iterating over them is a nice way to keep your code looking clean.</li></ul><p>2. Find all paths to leaves (ie, 2–3–9, 2–3–4, 2–8–7, 2–8–1)</p><p>3. Find the longest sequential path</p><p>Decision — because problems 2 and 3 seemed to share a lot in common, I decided to use one function to do both.</p><pre><strong>const </strong>allPaths = <strong>function</strong>(node) {<br>  // get all paths to leaves and longest, <br>  // increasing by one, sequence<br><br>  <strong>let </strong>maxSequence = 1,<br>   paths = [];<br><br>  <strong>const </strong>_recurse = <strong>function</strong>(node, currentSequence, currentPath) {<br><br>    <strong>if</strong>(node.value - currentPath[currentPath.length - 1] === 1)<br>      currentSequence++;<br>    <strong>else<br>      </strong>currentSequence = 0;<br><br>    currentPath.push(node.value);<br><br>    <strong>if</strong>(!node.left &amp;&amp; !node.right) {<br>      // at a leaf, compare currentSequence to maxSequence<br>      <strong>if</strong>(currentSequence &gt; maxSequence)<br>        maxSequence = currentSequence;<br><br>      paths.push(currentPath.slice());<br>      <strong>return</strong>;<br>    }<br><br>    <strong>if</strong>(node.left)<br>      _recurse(node.left, currentSequence, currentPath.slice());<br><br>    <strong>if</strong>(node.right)<br>     _recurse(node.right, currentSequence, currentPath.slice());<br>  };<br><br>  _recurse(node, 1, []);<br>  <strong>return </strong>{paths, maxSequence};<br>};</pre><p>A few notes on the above code…</p><ul><li>I’m using the slice method so that each new stack frame will have its own copy of the currentPath. Using this strategy, when the stack frame is popped off the stack, the frame under it will have a currentPath that accurately reflects its state. If currentPath was passed in without using the slice method, the underlying array would be mutated, and the state in each stack frame would be altered.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*1cAJhg4opCn2W3lDZFqgbw.png" /></figure><ul><li>{paths, maxSequence} is equivalent to {paths: paths, maxSequence: maxSequence} — keeps the code looking clean.</li></ul><blockquote>If you’re finding this content helpful in some way, don’t be shy, give me a clap :-) Thanks!</blockquote><p>4. Invert the Binary Tree from the earlier problem</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*ZTF_Q07nsqnx0GjFn-eiiQ.png" /></figure><pre><strong>const </strong>invertTree = <strong>function</strong>(node) {<br><br>  <strong>const </strong>queue = [node];<br>  <strong>let </strong>currentNode,<br>    temp;<br><br>  <strong>while</strong>(queue.length) {<br>    currentNode = queue.shift();<br>    <strong>if</strong>(!currentNode) <strong>continue</strong>;<br><br>    temp = currentNode.left;<br>    currentNode.left = currentNode.right;<br>    currentNode.right = temp;<br><br>    queue.push(currentNode.left, currentNode.right);<br>  }<br>};</pre><p>A few notes on the above code…</p><ul><li>Again, the queue is proving to be useful.</li><li>In order to test this code, I wrote a standard in-order traversal.</li></ul><pre><strong>const </strong>traverse = <strong>function</strong>(node, arr) { // in order traversal<br>  <strong>if</strong>(!node) <strong>return</strong>;<br><br>  traverse(node.left, arr);<br>  arr.push(node.value);<br>  traverse(node.right, arr);<br>};</pre><ul><li>Then used the following code to verify that the inversion worked...</li></ul><pre><strong>let </strong>arr = [];<br>traverse(root, arr);<br>console.log(&#39;Tree before inversion &#39;, arr);<br><br>invertTree(root);<br>arr = [];<br>traverse(root, arr);<br>console.log(&#39;Tree after inversion &#39;, arr);</pre><p>And that wraps it up! If you made it this far, I commend you on your focus ;-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=100e37eea0a3" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/binary-tree-problems-100e37eea0a3">Binary Tree Problems.</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Wonderful World With Web Sockets]]></title>
            <link>https://codeburst.io/web-sockets-a11360492ddd?source=rss-ad95e1d4696e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a11360492ddd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Reuben Nahouraii]]></dc:creator>
            <pubDate>Mon, 10 Jul 2017 03:50:17 GMT</pubDate>
            <atom:updated>2017-10-03T12:35:01.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6haqwpiXeLUSinF1g1ySg.jpeg" /></figure><p>Web Sockets… Why should I use them? What problem do they solve? Those questions, in addition to how to use them, are within the scope of this blog post. So, if you’re interested, please continue to read, if not, no offense taken… <a href="http://www.cutestpaw.com/wp-content/uploads/2011/11/cute-dog1.jpg">click me :-)</a> ← click either way…</p><p>You should use web sockets because ‘I say so.’ Phew, that question was easier to answer than I had originally anticipated. I guess the latter question might be the more challenging one to answer ;-)</p><p>Time to get serious. What problem does web sockets solve? Web sockets provide a protocol that allows a client to receive information from a server, via a server push, after an initial connection has been established. Typically, using HTTP, a client sends a request to a server, the server sends back a response, and then the connection is terminated. However, leveraging the web socket protocol, a connection can persist as long as it may be needed.</p><p>Let’s write a little code illustrating how to use web sockets, and perhaps, the WHY will become clear (if it isn’t transparent, just yet).</p><p>Using npm, we can install <a href="https://www.npmjs.com/package/socket.io-client">socket.io-client</a> and <a href="https://www.npmjs.com/package/socket.io">socket.io</a>, through terminal, with the following commands.</p><pre>npm i socket.io socket.io-client</pre><p>Now that we have a socket server and client, presumably, available in our node_modules directory, we can require and import them, respectively, for use.</p><p>First, let’s handle setting up sockets on the server (using the <a href="https://expressjs.com/">Express Framework</a>).</p><pre><strong>const </strong>app = require(&#39;express&#39;)();</pre><pre><strong>const </strong>server = app.listen(3000, <strong>function</strong>() {<br>  console.log(&#39;listening on port 3000&#39;);<br>});</pre><pre><strong>const </strong>io = require(&#39;socket.io&#39;)(server);<br><br>io.on(&#39;connection&#39;, (socket) =&gt; {<br>  console.log(&#39;socket connection made to socket &#39;, socket.id);<br>});</pre><p>At this point, we have successfully set up server-side sockets, but they really aren’t doing anything interesting, just yet… They are simply logging a message each time a unique socket connection is made.</p><p>Let’s add something useful. How about, each time a post is made to a message board, we update the message board that is being rendered on each client’s computer.</p><pre>app.post(&#39;/message&#39;, <strong>function </strong>(req, res) {</pre><pre>   <strong>const</strong> message = req.body;</pre><pre>   //  put message in database<br>   database.add(message);</pre><pre>   // send message out to all sockets (not the use of io)<br>   io.sockets.emit(&#39;topicCreated&#39;, {message});<br>});</pre><p>Now we have a server that is ready to receive posts and will update all the client computers with the new message. The next step is to set up a socket connection on the client.</p><pre><strong>import </strong>io <strong>from </strong>&#39;socket.io-client&#39;;</pre><pre>socket.on(&#39;connect_error&#39;, <strong>function</strong>(err) {<br>  console.log(&#39;error connecting to server&#39;);<br>});<br><br>socket.on(&#39;topicCreated&#39;, ({message}) =&gt; { <br>  console.log(message);<br>});</pre><blockquote>If you’re finding this content helpful in some way, don’t be shy, give me a clap :-) Thanks!</blockquote><p>And that is it! If you have been following along, congrats, you’ve just implemented web sockets! Sure, right now we are simply logging the message that comes from the server to the console; when really, we should be rendering the message to the message board. But that is out of scope for this blogpost. The important takeaway is that the client doesn’t have to request the new information; rather, the information is sent by the server as it becomes available.</p><p>I hope that you feel empowered, if you didn’t already, to give web sockets a try on your next project. They really help us (programmers, that is) in our quest to facilitate an awesome user experience for all those that use our software!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a11360492ddd" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/web-sockets-a11360492ddd">The Wonderful World With Web Sockets</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promises.]]></title>
            <link>https://codeburst.io/promises-918cb3607fc?source=rss-ad95e1d4696e------2</link>
            <guid isPermaLink="false">https://medium.com/p/918cb3607fc</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Reuben Nahouraii]]></dc:creator>
            <pubDate>Mon, 26 Jun 2017 19:33:57 GMT</pubDate>
            <atom:updated>2017-09-09T14:35:15.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtCLFPDOCbMSMNUKdrT8kg.jpeg" /></figure><p>When I initially learned about Javascript Promises, they seemed obscure, and honestly, I failed to grok the value proposition. At the time, I felt comfortable with asynchronous behavior using callbacks and didn’t see any point in stirring what appeared to be a pot at equilibrium. Enter, database queries with node… The aforementioned pot went from stasis, to a rolling boil, to an outright tempest. In the midst of the tumult, I made a promise and was able quell the gale. Now, I am a true believer, a zealot, even.</p><p>So, what is a Javascript Promise and when would it be in my best interest to use one? Well, I think that answering the latter will help with an understanding of the former. In the world of asynchronous code, callbacks become requisite, as halting code execution in order to wait for an outside task to complete would make for a really abhorrent user experience. Callbacks are used in order to facilitate synchronous behaviour in an async world. Which leads, inevitably, to code styles as such:</p><pre>readDataFromFile(&#39;path/to/file&#39;, (err, data) =&gt; {<br>   sendDataToWebsite(data, (err, response) =&gt; {<br>       writeResponseToFile(response, (err, success) =&gt; {<br>           console.log(&#39;Information was written&#39;, success);<br>       });<br>   });<br>});</pre><p>As you can see, the code is already starting to look a bit unwieldly, and this is only three async operations (without even introducing error handling). So, let’s introduce error handling and see what happens :-)</p><pre>readDataFromFile(&#39;path/to/file&#39;, (err, data) =&gt; {<br>  <strong>if</strong>(!err) {<br>    sendDataToWebsite(data, (err, response) =&gt; {<br>      <strong>if</strong>(!err) {<br>        writeResponseToFile(response, (err, success) =&gt; {<br>          <strong>if</strong>(!err) {<br>            console.log(&#39;Information was written&#39;, success);<br>          } <strong>else </strong>{<br>            console.error(&#39;error writing response to file&#39;, err);<br>          }<br>        });<br>      } <strong>else </strong>{<br>        console.error(&#39;error sending data to website&#39;, err);<br>      }<br>    });<br>  } <strong>else </strong>{<br>    console.error(&#39;error reading data from the file&#39;, err);<br>  }<br>});</pre><p>Wow, that got ugly real quick. As I hope that I have clearly illustrated, callbacks can create a codebase that is difficult to read, write, and generally, just ugly to look at. Fear not, I promise that promises will right this wrong. Let’s refactor the above code and pretend, for now, that each one of the above functions returns a promise.</p><pre>readDataFromFile(&#39;path/to/file&#39;)<br>  .then(data =&gt; {<br>    <strong>return </strong>sendDataToWebsite(data);<br>  })<br>  .then(response =&gt; {<br>    <strong>return </strong>writeResponseToFile(response);<br>  })<br>  .then(success =&gt; {<br>    console.log(&#39;Information was written&#39;, success);<br>  })<br>  .catch(err =&gt; {<br>    console.error(&#39;err&#39;, err);<br>  })</pre><p>I must admit, there is something quite satisfying about transforming that ugly pre-promises codebase to something more… hmmm, palatable. Perhaps, palatable is a bit too tepid. I think that delightfully delicious is more apt :P</p><blockquote>If you’re finding this content helpful in some way, don’t be shy, give me a clap :-) Thanks!</blockquote><p>I pray that the why of promises has penetrated deep into your bowels. That is has inextricably attached itself to the neurons that fire callbacks. Good. Now, let’s peek into the black box and witness the genesis of a promise.</p><pre><strong>let </strong>readDataFromFile = <strong>function</strong>(pathToFile) {<br>  <strong>return new </strong>Promise((resolve, reject) =&gt; {<br>    readFile(pathToFile, (err, data) =&gt; {<br>      <strong>if</strong>(err) {<br>        reject(err);<br>      } <strong>else </strong>{<br>        resolve(data);<br>      }<br>    });<br>  });<br>}</pre><p>Here, we have written the readDataFromFile function in a way that utilizes the promise constructor. If you are familiar with the way that error handling with callbacks in node is usually handled, then this code should feel somewhat familiar. Check this out.</p><pre>readFile(pathToFile, (err, data) =&gt; {<br>   <strong>if</strong>(err) {<br>      console.error(&#39;error reading from file&#39;, err);<br>   } <strong>else </strong>{<br>      // do something with data<br>   }<br>});</pre><p>As you can see, essentially, we are just wrapping a normal async function (readFile) in a promise and calling reject or resolve, depending on if we have an error or success. It is really that simple. If resolve is called, the <strong>then</strong> method will be invoked, but if we call reject, the <strong>catch</strong> method will be invoked. And because we are returning a promise from each <strong>then</strong> method, we can continue to chain them together to make beautifully readable code.</p><p>If you haven’t already been using promises, my hope is that you feel empowered to give them a try. And if you have, I hope that you were still able to find something interesting in this blog post. If not, my apologies… When you feel comfortable with the concept of promises, I suggest that you check out <a href="http://bluebirdjs.com/docs/getting-started.html">bluebird.js</a>. I would love to begin discussing bluebird.js, but I think that is a blog post best left for another day…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=918cb3607fc" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/promises-918cb3607fc">Promises.</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is recursion deserving of the hype?]]></title>
            <link>https://medium.com/@reubennahouraii/recursion-365544104f48?source=rss-ad95e1d4696e------2</link>
            <guid isPermaLink="false">https://medium.com/p/365544104f48</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Reuben Nahouraii]]></dc:creator>
            <pubDate>Fri, 16 Jun 2017 02:55:44 GMT</pubDate>
            <atom:updated>2017-09-14T19:46:18.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-_ByYXCjiha100bxUDrhQ.jpeg" /></figure><p>Elegant, succinct, academic… When I think of recursion, these are the words that permeate my mind-space. Crafting an elegant recursive solution to a problem may be seen as a rite of passage for many software engineers. Once you have a handle on the recursive paradigm of thought, you can wield it to solve coding puzzles with minimal lines of code. You will have finally arrived at the place where you always knew you wanted to be… Maybe. Is recursion really deserving of all the hype? I’m not sure, but let’s find out.</p><p>First, let’s start off with a canonical recursive problem, ie, finding the factorial of a given number, <em>n.</em></p><pre><strong>let </strong>factorial = <strong>function</strong>(n) {<br>  <strong>return </strong>n === 0 ? 1 : n * factorial(n - 1);<br>};</pre><p>Denying the elegance of this solution would be an exercise in futility; however, one might argue that the iterative approach is easier to read.</p><pre><strong>let </strong>factorial = <strong>function</strong>(n) {<br>  <strong>for </strong>(<strong>var </strong>product = 1; n &gt; 0; n--) {<br>    product *= n;<br>  }<br>  <strong>return </strong>product;<br>};</pre><p>In order to deem whether or not recursion is a worthy recipient of the adoration of so many, I think it best to try and understand the cost and benefits associated with it. Let’s begin with the benefits.</p><p>The nature of recursion lends itself to pithy code. As there is a positive correlation between lines of code and maintenance costs, this results in a plus one for recursion.</p><p>At times you may find yourself dealing with a data structure that may be variable in length, like a tree. Recursion is a good fit for iterating over something of unknown depth because it naturally wants to continue down the path. Another point for recursion…</p><p>Though I might definitely be missing a benefit or two, I feel that the aforementioned benefits of recursion are the most obvious to me. Now, we should attempt to understand the costs that accompany these benefits…</p><p>Although recursive code may, at times, be more succinct, it can definitely be more difficult to read and understand the author’s intent. In addition, debugging recursive code can be, at times, an arduous task fraught with frustration. If you are wondering what makes debugging recursive code more daunting than other code, then you are wondering just the thing I am about to address, nice :-). I find that debugging recursive code can prove to be a daunting task because as new execution contexts are created, with each recursive call, it can be challenging to discern which execution context you are currently in, as the variables associated with each execution context share the same names. This difficulty debugging definitely results in a negative point for recursion.</p><p>Another cost that is inherent to a recursive solution is the cost associated with function invocation. When a function is invoked, a stack frame is created; when a function finishes, the stack frame is popped off the stack. The invocation of a function is an expensive process because a new execution context has to be created each time, and each execution context has a set of variables that are available to that context. When writing a recursive solution, you end up calling the same function many times... Subtract a point from recursion.</p><blockquote>If you’re finding this content helpful in some way, don’t be shy, give me a clap :-) Thanks!</blockquote><p>As I mentioned earlier, recursive code is apt for a certain type of problem, ie, ones where the depth that needs traversal is unknown; however, certain problems do not lend themselves to a recursive solution. One such problem that comes to mind is a breadth-first traversal of a binary tree. Sure, it can be solved with recursion (through some creative programming), but in this case, I find that the iterative approach is far more suitable.</p><p>Below is code for a breadth-first traversal that pushes nodes into an array if they pass a test based on their value and depth.</p><pre>Tree.prototype.BFSelect = <strong>function</strong>(filter) {<br>  <strong>let </strong>newArr = [], queue = [], depthQue = [];<br><br>  <strong>let </strong>node, depth;<br>  queue.push(<strong>this</strong>);<br>  depthQue.push(0);<br><br>  <strong>while</strong>(queue.length) {<br>    depth = depthQue.shift();<br>    node = queue.shift();<br><br>    <strong>if</strong>(filter(node.value, depth)) {<br>      newArr.push(node.value);<br>    }<br><br>    depth++;<br>    node.children.forEach(childNode =&gt; {<br>      queue.push(childNode);<br>      depthQue.push(depth);<br>    });<br>  }<br><br>  <strong>return </strong>newArr;<br>};</pre><p>An iterative approach to this kind of problem (BF binary tree traversal) seems like the logical solution because you are wanting the traverse the tree level by level. As mentioned earlier, recursion tends to naturally want to follow a path all the way to the bottom, at which point it begins its journey back through the stack frames (not an ideal paradigm for a problem such as this).</p><p>A confession… I started writing this article with a fairly negative view of recursion; however, during the process of writing this article, which naturally required many moments of reflection, I find that I have reached an understanding, and acceptance, of recursion that I had not formerly had. I still think that an iterative approach is probably more suited for most situations, for reasons that I touched on earlier, but I won’t write-off recursion just yet.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=365544104f48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backbone vs React vs Angular: data passing and event listener.]]></title>
            <link>https://medium.com/@reubennahouraii/backbone-vs-react-vs-angular-data-passing-and-event-listener-668b3617b783?source=rss-ad95e1d4696e------2</link>
            <guid isPermaLink="false">https://medium.com/p/668b3617b783</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[backbonejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Reuben Nahouraii]]></dc:creator>
            <pubDate>Sun, 11 Jun 2017 23:58:05 GMT</pubDate>
            <atom:updated>2017-09-22T04:09:04.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NajqzWSDorZqdBtlgDk__Q.jpeg" /></figure><p>Backbone vs React vs Angular: data passing and event listener.</p><p>Every interactive application has paths for data to flow. To the uninitiated, these paths may be hard to discern. At first, it may feel as though you are traveling through an unfamiliar wilderness during the eve; however, just as the dawn is sure to come, so too, will understanding illuminate your mind. The paths, that only minutes before were shrouded in darkness, exist, defined in the light.</p><p>React, Backbone, and Angular, all have paths of a similar nature. As the state of the application changes, due to actions by a user, data is often fetched, manipulated, and rendered. How are the components, which are isolated by nature, to communicate with one another? The answer is interface. Just as auditory data leaves our body primarily through our mouths and is primarily received through our ears, data is passed through one part of BRA (Backbone, React, Angular) interface, but received by another.</p><p>While all three frameworks have syntactical differences, they share many patterns when it comes to moving data. When initializing a backbone view, the view is often linked to a model, or a collection of models, where listeners are set. The event listeners are attached to the model, firing when a particular event happens. This might indicate a change of state in the model, or perhaps, an event triggered by a user.</p><pre><strong>const </strong>VideoPlayerView = Backbone.View.extend({<br><br>  initialize: <strong>function</strong>() {<br>    <strong>this</strong>.listenTo(<strong>this</strong>.collection, &#39;select&#39;, <strong>this</strong>.selectVideo);<br>  },<br><br>  selectVideo: <strong>function</strong>(selection) {<br>    <strong>this</strong>.model = selection;<br>    <strong>this</strong>.render();<br>  },<br><br>  render: <strong>function</strong>() {<br><br>    <strong>if </strong>(<strong>this</strong>.model) {<br>      <strong>this</strong>.$el.html(<strong>this</strong>.template(<strong>this</strong>.model.attributes));<br>    } <strong>else </strong>{<br>      <strong>this</strong>.$el.html(&#39;&lt;div class=&quot;loading&quot;&gt;Please wait...&lt;/div&gt;&#39;);<br>    }<br>    <strong>return this</strong>;<br>  },<br><br>  template: templateURL(&#39;src/templates/videoPlayer.html&#39;)<br><br>})</pre><p>In the above example, an event listener is being placed on the select event of the collection. When a model is selected, the event will bubble up through the collection and trigger the select event, which will in turn, change the model associated with the view, and thereby render the new model.</p><p>Let’s explore how React handles a similar situation.</p><pre><strong>const </strong>VideoPlayer = (<strong>props</strong>) =&gt; (<br>   &lt;iframe<br>      src={`https://www.youtube.com/embed/<br>          ${<strong>props</strong>.video.id.videoId}?autoplay=1`}<br>      allowFullScreen&gt;<br>   &lt;/iframe&gt;<br>   &lt;h3&gt;{<strong>props</strong>.video.snippet.title}&lt;/h3&gt;<br>   &lt;div&gt;{<strong>props</strong>.video.snippet.description}&lt;/div&gt;<br><br>  );</pre><p>Bring your attention to the <strong>props</strong> argument that is being passed into the anonymous function. The argument that is passed to the anonymous function when VideoPlayer is instantiated, will have any property information that the parent component wishes to impart on its child. Through this mechanism, the parent component can pass down information that the child component can use to render itself. If any property information changes upstream, that is being passed through the props argument, those changes will be reflected in the child component. In addition, the parent component can pass through bound functions as properties on the props argument that can be attached to any event listener along the way. The VideoPlayer component above is stateless; however, if its parent component has state, it will cause VideoPlayer to render anew when relevant changes to the parent’s state occur.</p><blockquote>If you’re finding this content helpful in some way, don’t be shy, give me a clap :-) Thanks!</blockquote><p>Data flows through Angular components in a similar way to what we have seen with Backbone and React. Typically, data flows from parent to child at the time of the child’s instantiation.</p><pre>&lt;video-player video=&quot;$ctrl.currentVideo&quot;&gt;<br>   &lt;h5&gt;videoPlayer component goes here&lt;/h5&gt;<br>&lt;/video-player&gt;</pre><p>The child binds the data that is coming in through a <strong>bindings</strong> property that exists on every component.</p><pre>angular.<em>module</em>(&#39;video-player&#39;)<br><br>.component(&#39;videoPlayer&#39;, {<br>  bindings: {<br>    video: &#39;&lt;&#39;<br>  },<br>  templateUrl: &#39;src/templates/videoPlayer.html&#39;,<br>});</pre><p>In the above example, the ‘<strong>&lt;’</strong> denotes that a one-way binding is occurring. This means that when the property changes in the parent, the child’s view will be re-rendered. This is different from a ‘<strong>=’</strong> which denotes a two-way data-binding. A two-way data-binding has the effect of updating the values in both the parent and child whenever the said property is altered, and re-rendering as necessary. Two-way binding is generally frowned upon, as it has some serious performance costs associated with it, and should only be used when absolutely necessary.</p><p>Once the data has been passed through to the child component, the child can choose to render the information. The syntax for displaying the information is as follows.</p><pre>&lt;h3&gt;{{$ctrl.video.snippet.title}}&lt;/h3&gt;<br>&lt;div&gt;{{$ctrl.video.snippet.description}}&lt;/div&gt;</pre><p>Notice the <strong>{{ }} </strong>and the use of the <strong>$ctrl</strong>. The mustaches (curly braces ;-) denote string interpolation. The expression inside will be evaluated, and the evaluated string will show up in the html. The $ctrl is not optional; it is referencing the scope of the controller that exists on the component. I realize that I haven’t discussed the controller, but I think it is fair to think about it as the place where the variables and methods associated with a given component live.</p><p>In Angular, similar to Backbone and React, data flows from child to parent, via events. A bound function is passed from parent to child during instantiation, and attached to an event of any of the parent’s descendants. When the said event is fired, the function that was passed down, runs. Because the <strong>this</strong> is bound to the parent’s scope, changes can be made in the parent which might then be reflected in its children.</p><p>I hope that this discussion has helped to illuminate the paths in your mind that are associated with data flowing through these frameworks. If you are still reading this…I appreciate you spending your time to do so :-)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=668b3617b783" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>