<?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 William Neal on Medium]]></title>
        <description><![CDATA[Stories by William Neal on Medium]]></description>
        <link>https://medium.com/@williamneal_79906?source=rss-23124f73e4ba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TEcLd8ClNIROdOkuGCESxQ@2x.jpeg</url>
            <title>Stories by William Neal on Medium</title>
            <link>https://medium.com/@williamneal_79906?source=rss-23124f73e4ba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 10:48:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@williamneal_79906/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[Things I wish I knew before adding a minimax function to a Noughts and Crosses game]]></title>
            <link>https://medium.com/@williamneal_79906/things-i-wish-i-knew-before-implementing-minimax-function-for-a-noughts-and-crosses-game-182ce4219e76?source=rss-23124f73e4ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/182ce4219e76</guid>
            <category><![CDATA[noughts-and-crosses]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[minimax]]></category>
            <category><![CDATA[tic-tac-toe]]></category>
            <dc:creator><![CDATA[William Neal]]></dc:creator>
            <pubDate>Mon, 07 May 2018 16:11:15 GMT</pubDate>
            <atom:updated>2018-05-07T16:24:23.031Z</atom:updated>
            <content:encoded><![CDATA[<p>There are a lot great guides out there on how to implement minimax function in the context of a game of Noughts and Crosses (Tic Tac Toe) (<a href="https://www.neverstopbuilding.com/blog/2013/12/13/tic-tac-toe-understanding-the-minimax-algorithm13">here</a>, <a href="https://medium.freecodecamp.org/how-to-make-your-tic-tac-toe-game-unbeatable-by-using-the-minimax-algorithm-9d690bad4b37">here</a>). Despite the availability of great guides, and it being a ‘trivial’ implementation of the minimax function I toiled many, many, many, hours to get the function to behave as it should. Instead of creating another ‘walkthrough’ on how to do it, here is what I wish I had known before setting off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*iJ8TKTtBGXf_i1EDIwu2hw.png" /></figure><p><em>Note: These pearls of wisdom that you can gleam here are the product of an implementation of minimax function in JavaScript.</em></p><p><strong>Recursion</strong></p><p>Recursion is hard. Normally it is a good idea not to visualise the implementation of a recursive function, lest otherwise <a href="https://media.giphy.com/media/26n78QtJt4LHeNXi0/giphy.gif">this</a>. Sometimes though there is no avoiding it if you must track down an undefined value. I felt overwhelmed and lost. Identifying the behaviour of the minimax function, as distinct from its implementation, gave me a reference point for my investigations.</p><p>The behaviour of the minimax functions mirrors that of the abstract data type known as <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">tree structure</a>. A minimax function must have these three things:</p><p>· Terminal condition — the condition that is met to exit recursion. In our case when either a winning game state is reached or when there are no further moves to make.</p><p>· Recursive step — a bigger and more complex problem is broken down into a series of simpler, self-invoking steps which collectively add up to the solution. In our case, it is when minimax is called when a particular game state does not meet the requirements of the terminal condition.</p><p>· A way to return the best move out of a series of possible moves. In our case, minimax function is called multiple times in a series of nested function calls, that resolve in a LIFO basis (last in first out), where the latest function call is also the inner most function call. The result is yielded from inner function to the outer function, with each outer function receiving and reducing multiple returned values from nested function calls and passes the optimal move up the scope chain. This phase only happens when all possible moves have been made.</p><p>Visualising this is a challenge. This is where thinking in terms of nodes I found to be useful. Nodes are sites in which pathways intersect, which in our case, is a more abstract way of saying that a particular game state has a range of moves available to it. There are three node types pertinent to us:</p><p>· Root node — this does not have a parent node, but may lead to child nodes. It is the first invocation of the maximin function.</p><p>· Internal node — a node with children. In our case, it is a game state that has available moves.</p><p>· Terminal node — a node without children. In our case it is when a game state has no moves available to it; either because of all moves have been made, or game winning state has been obtained.</p><p>Thinking in these terms helped me to set expectations of what I meant to see and avoid confusing different ‘levels’ of the function.</p><p>The maximin function, does basically two things:</p><p>· Generates all the paths between parent nodes to child nodes</p><p>· Plot pathway from the root node to the terminal node that results in the non-victory of the opposition.</p><p>Therefore if you encounter a bug, i.e. if the maximin function does not return a value, or, it returns the wrong value, it will fall into one of three categories of bugs:</p><p>· Particular path between parent and child node should be there but isn’t i.e. move that should be available, is not available. The returned value whilst suboptimal, is notionally correct in so far as the available pathways available to it. Investigate the functions related to terminal condition and recursive step.</p><p>· All the pathways that should be there, are there, but it returns the wrong value. Investigate the functions related to selecting the best move.</p><p>· Expected available move for a given game state is not there, and given the incomplete range of available moves, the returned value is also not as expected. Because plotting the optimal pathway is dependent on having the full range of moves, prioritise fixing functions related to terminal condition and the recursive step.</p><p><strong>Debugging</strong></p><p>One you are aware of what should be happening at any one point in time, it should greater purpose to your debugging efforts. This activity can be further supported by doing the following:</p><p>· I decomposed my minimax function into constituent parts, and unit tested each part. This takes time, but less time than searching for origins of an undefined value in a gnarly mega function.</p><p>· Often I found that a function worked whilst I unit tested it, but when I integrated it with other functions it produced unexpected results. The is one of two causes, a function located downstream was producing unexpected undefined values, or my assumptions of input were incorrect.</p><p>· Instead of having the minimax function returning primitive values i.e. a number representing move index, return objects which contain ‘meta data’ such as move, whose turn it is, current board state, turn number and score. This will help you to locate in which iteration a bug originated.</p><p>· If you take the above advice onboard, beware of difference between a <a href="https://we-are.bookmyshow.com/understanding-deep-and-shallow-copy-in-javascript-13438bad941c">shallow copy and deep copy</a> of an object. If you make a shallow copy of the root node, in the course of generating child nodes, the child node’s property, an array containing the game state, is actually a reference to the game state of the root node. Any changes made to this array at the level of a child node i.e. making a new move, is actually being reflected at the level of the root node. This causes havoc. Remember to deep clone.</p><p>· Represent free moves with null values. This makes it easier to test different scenarios with ‘dummy moves’ i.e. when testing different game winning scenarios, moves that are non-pertinent can be represented with a character that isn’t X/O. In this way it narrows the range of available moves, without interfering with the function checking for a game winning state.</p><p>· Liberal use of console.log statements is good. Console.log statements in conjunction with Chrome Developer tools is better. Use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger">debugger</a> statement.</p><p><strong>Minimax returning non-optimal move</strong></p><p>So your minimax function kinda works. If you want it to work properly so that it makes the optimal move in every circumstance:</p><p>· Depending on how you calculate the ‘optimal path’, sometimes the move returned leads to a non-optimal victory i.e. selecting a combination moves that leads to victory in several moves instead of immediately. Another example… the computer should never be in a losing position. However, if your app has the ability to turn on player verses computer mode halfway through a game, and the computer assumes a player role that will ultimately lead to a defeat, sometimes the computer will throw itself on its own sword instead of playing to the bitter end. You can avoid this by factoring into a ‘temporal discount’ into points awarded for a winning state. I used the turn number to discount the points value awarded. This will favour moves that result in winning scenarios that happen sooner.</p><p>· The points awarded for a winning scenario should be sufficiently large to allow for the fact that it will be discounted (you don’t want a positive score to become negative, or a negative score to become positive).</p><p>· Undefined values creeping into map() and reduce() functions which are responsible for identifying and generating new game states.</p><p>· If you are using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">reduce</a> function with a initialValue to select the winning move, be attentive to the presence of undefined values in the array. If the initial value is used to access an item in an array, and comes across an undefined value, it may auto default to selecting the first item in the array (initialValue = 0).</p><p><strong>Sources of undefined values</strong></p><p>· Recursive functions need at least one terminal condition to exit the recursion. The minimax has two, when a game winning state has been reached AND when there are no further moves to make. Be sure to include both.</p><p>· If you have taken on board previous advice for the minimax function to return objects and not primitive values, be sure that when you are referencing properties of an object that you spell them correctly!</p><p><strong>Summary</strong></p><p>Bringing in bit of “tree theory” will not be to everyone’s taste, I found it useful way to focus on the game state and what should be happening and away from the implementation details of the recursive function. This acted as my compass when I started digging into the implementation detail and stepping through function calls with Chrome Developer tools.</p><p>I found implementing the minimax function a steep challenge but feel that I have been richly rewarded for my efforts. There are other ways of implementing a player verses commuter mode in a Noughts and Crosses game, however I would strongly encourage anyone who likes a challenge to give it a go.</p><p>If you found this article helpful, please consider giving it a clap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=182ce4219e76" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recursion in javaScript: factorial example]]></title>
            <link>https://medium.com/@williamneal_79906/recursion-in-javascript-factorial-example-1b2fe731e14e?source=rss-23124f73e4ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b2fe731e14e</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[William Neal]]></dc:creator>
            <pubDate>Sun, 11 Mar 2018 15:45:10 GMT</pubDate>
            <atom:updated>2018-03-11T15:45:10.688Z</atom:updated>
            <content:encoded><![CDATA[<p>Recursion is away to break up a large problem into several smaller problems, which considered in isolation are easier to solve, but which collectively add up to the answer to the larger problem.</p><p>In the broadest sense, this is what all coding is all about — breaking problems down into manageable chunks. What is different about recursion is that it is self-referential, that is, the function invokes itself. The self consistency of the solution is why some people find recursive solutions elegant, but equally for the uninitiated, recursion can seem mind bending.</p><p>However with a good grasp of how functions operate, you have all the tools necessary to understand how recursion works in javaScript.</p><ul><li>when a function is called, code execution in the current context stops, and control is passed over to a newly created context for that function. The function executes it’s statements until it hits the return statement (or runs out of statements to execute), at which point the function returns and passes control back to the original context, and code execution resumes.</li><li>a function call can happen from within the global scope or from within the context of the local scope of a function body i.e. a nested call.</li><li>The nested call can be self-invoking, because javaScript engine tracks each function call as a separate and discreet context in the call stack.</li><li>Nested functions can “see” the variables in the containing functions, and contained functions can pass values to containing functions via the return statement</li></ul><p><strong>Bad example: calculating factorials</strong></p><p>Let us work through canonical example: calculating factorials.</p><blockquote>5! = 1*2*3*4*5</blockquote><p>Breaking the problem down we have to do the following:</p><ul><li>create a series of descending numbers</li><li>multiple each number with each other</li></ul><p><strong>For loop solution</strong></p><p>How would you tackle this problem without recursion? Probably utilizing a for loop to create a series out of the given factorial:</p><pre>function factorial(num){<br> let runningTotal = 1;</pre><pre>for(let i = 1; i &lt;= 5; i++){<br> if(num===0){<br>    return 1;<br> } else{<br>    runningTotal =* i;<br>       }<br> }<br> return runningTotal;<br>}</pre><p>A variable is created to track the running total because each iteration overwrites itself. The variable will also be used in calculations themselves; it needs to be initialized as 1 otherwise the function would only return the result 0 (0 multiplied by any number is still 0). Bizarrely one thing to remember about factorials is that 0! = 1, so we need to explicitly include a condition to check whether num===0.</p><p>The key take away from this, is that a variable is created to explicitly keep track of the running total. Lets now compare this to a recursive solution:</p><p><strong>Recursive solution</strong></p><p>There are two basic ingredients for recursion:</p><ul><li>base case — the condition that needs to be met to stop recursion</li><li>recursive step — step which is repeatably performed</li></ul><p>Note the similarity in structure with a while / for loop, in having an explicit exit condition and an action which is repeatedly executed. Lets now apply the the above ingredients to the problem:</p><pre>function factorial(num){<br>  //base case<br>  if(num===0){<br>   return 1;<br>  } else{<br>   //recursive step<br>   return num*<strong>factorial(num-1)</strong>;<br>  }<br> }</pre><p>The first thing that should strike you in the above code is the absence of a variable that is explicitly keeping track of the running total and that the recursive step is utilizing a nested, self invoking, function call which is typical of a recursive function. What is going on?</p><p>Let us recall what we are doing:</p><ul><li>create a series of descending numbers</li></ul><p>Each time the recursive step is executed, a function call is made which generates its own distinct context. If the given factorial was 5!, the recursive step would be generated in total six times:</p><blockquote>factorial(5), factorial(4), factorial(3), factorial(2), factorial(1),<strong> factorial(0)</strong></blockquote><p>The sixth function call in the stack triggers the base case, ending the recursive steps. At this point in time, we have only created a series of descending numbers. Despite each function call being distinct, each function call is linked with the previous function call, not only due to the scope chain, but because <em>each function call acts as a value for the previous function</em>. We haven&#39;t yet began to calculate the result of the individual function calls, let alone the final result.</p><ul><li>multiple each number with each other</li></ul><p>The function calls are stored in a call stack which operates on a last in first out (LIFO) basis. The last function call was factorial(0) which triggered the base case, which means that the returned value 1 can finally be yielded to Factorial(1), which can now finish its calculation and yield a value to its containing function call (factorial(2)) etc…</p><blockquote>factorial(0) =&gt; 1 (base case returns 1)</blockquote><blockquote>factorial(1) =&gt; 1</blockquote><blockquote>factorial(2) =&gt; 2</blockquote><blockquote>factorial (3) =&gt; 6</blockquote><blockquote>factorial(4) =&gt; 24</blockquote><blockquote>factorial(5) =&gt; 120 (final result — no more function calls on the stack)</blockquote><p>The key take away in this example, is that there is no need for a variable to track the running total, because the result is only worked out after the fact, that is, when the base case is met.</p><p><strong>Comparing approaches</strong></p><p>What is most striking for me is the similarity of approaches to this particular problem. They both generate the series of descending numbers in a similar way (albeit in different contexts, one utilizing a control structure, the other a series of function calls), both calculate factorial in a similar way (one needs the help of a running total, the other doesn’t). This amounts to a superficial difference in implementation but not in how one approaches a problem.</p><p>What new powers do I have approaching a problem with recursion compared to using iteration? With the factorial example the answer to this question is not so clear, and it obfuscates fundamental philosophical differences between the approaches.We will have wait for other examples to discover the true power of recursion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b2fe731e14e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Summary: Of the difference between interpreted and compiled languages]]></title>
            <link>https://medium.com/@williamneal_79906/summary-of-the-difference-between-interpreted-and-compiled-languages-c58639b87c19?source=rss-23124f73e4ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/c58639b87c19</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[interpreters]]></category>
            <dc:creator><![CDATA[William Neal]]></dc:creator>
            <pubDate>Sun, 18 Feb 2018 13:38:44 GMT</pubDate>
            <atom:updated>2018-02-18T14:29:39.811Z</atom:updated>
            <content:encoded><![CDATA[<p>Source code is a set of statements telling a computer to do something that is understandable by humans but not computers. JavaScript, Python, C#, Java etc… are examples of source code. The intended audience of source code is not computers, but other humans. Source code is a way for humans to talk about the instructions we want to give to computers.In order for a computer to understand the statements contained in source code it needs to be translated into machine code.</p><p>How these instructions are translated from being human readable to machine readable is an implementation detail of a particular language. That is, it is not concerned with a languages particular syntax, what it “is”, but how a particular language is put into effect.</p><p>There are two ways of categorizing how human readable instructions are translated into machine readable code.</p><ol><li>Source code that is interpreted into machine code at run time</li><li>Source code which is first compiled into an intermediary language, which is then converted into machine code at run time and executed.</li></ol><p>Interpreted source code is stepped through, line by line, and executed at runtime. This has advantages when the code is in development as the interpreter would stop when it encounters an error. This helpful for debugging but comes at a cost for performance. If a particular instruction is run multiple times, why spend resources processing the instruction from source code each time? It would be better to translate the instruction from source code once, and reuse the result multiple times.</p><p>Source code which is compiled, is analysed wholesale, producing an intermediary language in which certain optimisations can be performed. This improves performance when the intermediary language is translated into machine code and executed at runtime. This comes at a price, the analysis performed of the source code that generates the potential optimizations takes time. The end user is protected from this cost because it occurs ahead of runtime. In the development phase, the compiler must analyse the code wholesale before flagging any errors, thus extending the development time for a product.</p><p>Today this distinction between languages which are interpreted and compiled has become increasingly blurred due to “<a href="https://stackoverflow.com/questions/95635/what-does-a-just-in-time-jit-compiler-do">just in time</a>” (JIT) compilation. Compilation, as outline earlier, happens ahead of runtime. <a href="https://blog.sessionstack.com/how-javascript-works-inside-the-v8-engine-5-tips-on-how-to-write-optimized-code-ac089e62b12e">JIT</a> compilation optimizes code synchronously <em>at run time</em>, through retaining a ‘memory’ of the source code that was previously ingested in order to predict whether newly ingested code should undergo optimization or not.</p><p>In summary source code which is interpreted can be a more pleasant experience for developers, but the code itself is executed in a less optimized manner. Source code which compilation ahead of run time benefits from an optimised code base, with the processing costs associated with optimisation falling in the development phase. JIT compilation makes a trade off between these characteristics, some of the code is optimized, of the code that is optimized, the processing cost of this optimization may not outweigh the performance benefits.</p><p>The narrative of interpreted code being nicer for developers (easier to debug), and compiled code being better for end user (faster programmes) again becomes more blurred due to changes in product lifecycle. It may have been better once upon a time to have front loaded the costs associated with optimization on the development phase. The upfront cost is more than made up in a product which would have a lifespan of perhaps 3–5 years. Now, once product is launched there is an expectation of ongoing development in response to user feedback. Longer development time means a product which less responsive to user feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c58639b87c19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Walk through of the official React’s Noughts and crosses tutorial: Part 1]]></title>
            <link>https://medium.com/@williamneal_79906/walk-through-of-the-official-reacts-noughts-and-crosses-tutorial-part-1-829abe52b1ce?source=rss-23124f73e4ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/829abe52b1ce</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[William Neal]]></dc:creator>
            <pubDate>Thu, 14 Dec 2017 08:44:02 GMT</pubDate>
            <atom:updated>2017-12-14T14:22:40.072Z</atom:updated>
            <content:encoded><![CDATA[<p>The tutorial can be found <a href="https://reactjs.org/tutorial/tutorial.html">here</a>, in part 1 we are going to walk through the vert first part of the tutorial “ Passing Data Through Props”.</p><p>The provided starter code sets ups three components:</p><p>· Square</p><p>Render returns a blank button</p><p>· Board</p><p>Has a RenderSquare method that invokes Square and a variable whose job is to track whose turn it is. Currently set to “Next player: X”.</p><p>It render returns nine squares which are organised in three rows of thee, each square invoking RenderSquare method and passing in a number corresponding to the order in which the square finds itself in.</p><p>· Game</p><p>Render returns the Board and a separate div containing game info such as whose turn it is.</p><p>My first observation is how the components are laid out in terms of increasing generalization. From low abstraction (Square), intermediate abstraction (Board), high abstraction (Game), lower levels of abstraction are invoked by components of a higher level of abstraction.</p><p>Components are encapsulated pieces of code. The first aim of the tutorial is to demonstrate how to pass props between components, and in doing so, how to pass information between different levels of abstraction.</p><p>Functions are encapsulated code, which accepts inputs in the form of passed in arguments, and outputs via the return statement. Instead of using a function call to pass in arguments, React uses elements to pass props to a component and the component outputs via render.</p><p>In this case Board’s render return calls its own method, RenderSquare, and passes in a number. RenderSquare is currently doing nothing with this passed in value.</p><p>We therefore modify RenderSquare’s react element, creating a new attribute that is assigned to the methods parameter. When method is invoked, the passed in value will be in turn be passed to Square as a prop.</p><pre>class Board extends React.Component {</pre><pre>renderSquare(i) {</pre><pre><strong>return &lt;Square value={i} /&gt;;</strong></pre><pre>}</pre><p>Currently Square simply returns a blank button, to display the passed in prop we inject an expression that refers to the prop:</p><pre>class Square extends React.Component {</pre><pre>render() {</pre><pre>return (</pre><pre>&lt;button className=&quot;square&quot;&gt;</pre><pre><strong>{this.props.value}</strong></pre><pre>&lt;/button&gt;</pre><pre>);</pre><pre>}</pre><pre>}</pre><p>Previously the app displayed nine blank squares, having now passed props to Square component the app’s squares now display numbers. In so doing it highlights the one-way data flow of React. Through convention, data is passed from outer, more generalized components, to nested components with lower levels of abstraction. Components in this way are functional, i.e. they receive props as an argument equivalent, yet use es6 class syntax to implement individual components in a highly structured way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=829abe52b1ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forays into React: Elements and Props]]></title>
            <link>https://medium.com/@williamneal_79906/forays-into-react-elements-and-props-d108fbaeaf42?source=rss-23124f73e4ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d108fbaeaf42</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript-frameworks]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[William Neal]]></dc:creator>
            <pubDate>Thu, 07 Dec 2017 23:10:19 GMT</pubDate>
            <atom:updated>2017-12-07T23:10:19.474Z</atom:updated>
            <content:encoded><![CDATA[<p>I jumped straight into the React tutorial and quickly became disillusioned following instructions without knowing the “why” of what I was doing. I am using this post to help think through React elements and stateless components.</p><p><strong>Elements</strong></p><p>JSX is a markup language which describes elements which will be rendered to the DOM from within a React component. In comparison to vanilla JS, they are the equivalent to function statements.</p><p>They may either be:</p><p>· Native DOM elements — &lt;div someAttribute=”someValue”/&gt;</p><p>· User created elements — components!</p><p>Elements are “appended” to the DOM through the use of Render(), which is basically a variation of document.appendChild().</p><p><strong>Components</strong></p><p>Components give form to elements and can either be a basic function or a special type of syntax sugar new to JS known as classes. Where functions have arguments which are passed values via function calls, components have “props” which are passed values via user defined attributes as part of an JSX element.</p><p>One of the key distinguishing features of JavaScript is that functions are first class citizens, meaning that they can behave like any other value. In this topsy-turvy world, form can become content, content becomes form as functions are passed in and out of other functions. In a similar manner component can become elements of other components.</p><p><strong>Summary</strong></p><p>In closing, if you have a degree of familiarity with vanilla JS, you are already familiar with React. The challenge is in recognizing common patterns between the two, and how it is implemented differently with React.</p><p>I suspect that the key to understanding React is in recognizing the role played by state and the immutability of props. My working hypothesis at the moment is that unlike the aforementioned vertigo inducing world of vanilla JS functions, React offers the relative stable distinction between state as form and immutable props as content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d108fbaeaf42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript can do lots of things at once despite being a single threaded language. How?]]></title>
            <link>https://medium.com/@williamneal_79906/javascript-can-do-lots-of-things-at-once-despite-being-a-single-threaded-language-how-8e9cdb6d5ae1?source=rss-23124f73e4ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e9cdb6d5ae1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[William Neal]]></dc:creator>
            <pubDate>Mon, 04 Dec 2017 19:54:02 GMT</pubDate>
            <atom:updated>2017-12-04T19:54:02.126Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript can only do one thing at a time, this is what is meant when we say that it is single threaded language. Once it starts a task, it will not move on to the next task until the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#Run-to-completion">original task is completed</a>. The call stack is what keeps track of what is going to be imminently executed and in what order; the execution context is the current task running in the present — the ‘now’ of the JavaScript engine.</p><p>The call stack is fed new tasks by the <a href="https://blog.carbonfive.com/2013/10/27/the-javascript-event-loop-explained/">event loop</a>, tasks which originate from an external queue. This external queue consists of endogenous tasks (new tasks generated from the items executed in the call stack) or exogenously via a multifaceted array of external web APIs.</p><p>If requests are made synchronously to these web APIs, the JavaScript engine will wait until it receives a response. The power of JavaScript lies in its ability to decouple the request from its response, which forms the basis of asynchronous programming. This means that the JavaScript engine after making the request can move onto the next item whilst “waiting” for the response. In this way, labour intensive tasks can be delegated to an external API without the phenomena of “<a href="https://developer.mozilla.org/en-US/Apps/Fundamentals/Performance/UI_Synchronicity">blocking</a>”.</p><p>This is why JavaScript is super popular for web programming, it allows for slick user experience through being able to ‘outsource’ tasks which eventually make their way back in the external queue, which are then ingested by the JavaScript engine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e9cdb6d5ae1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You probably shouldn't use XHR for building a Random Quote Generator]]></title>
            <link>https://medium.com/@williamneal_79906/you-probably-shouldnt-use-xhr-for-building-a-random-quote-generator-973b76ee20d0?source=rss-23124f73e4ba------2</link>
            <guid isPermaLink="false">https://medium.com/p/973b76ee20d0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[xmlhttprequest]]></category>
            <category><![CDATA[freecodecamp]]></category>
            <category><![CDATA[xhr]]></category>
            <dc:creator><![CDATA[William Neal]]></dc:creator>
            <pubDate>Sun, 06 Aug 2017 10:59:37 GMT</pubDate>
            <atom:updated>2017-08-06T11:01:33.044Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>You probably shouldn&#39;t use XHR for building a Random Quote Generator</strong></p><p>This post is a testimony to me stumbling down a blind alley, but learning a lot about ajax calls in the process, particularly in the context of making a random quote generator for the Free Code Camp Intermediate Front End Development Project. If you are a fellow camper, or you want to learn more about making ajax calls with vanilla JS— read on!</p><p>In my first pass of building a random quote generator I simply made an array of objects, with each object containing a quote and author. Using Math.random() combined with Math.floor() I randomly accessed the array and generated a quote in response to a user clicking a button. When I was attending a Free Code Camp meetup I noticed that the other participants utilized API call in order to generate their quotes. This inspired me to replicate this functionality.</p><p>A popular way seems to use JQuery to make the API calls. I like to code with vanilla JS as much as possible. When using libraries, such as JQuery, the implementation details of what you are doing get abstracted away. I wanted to better understanding of what happens under the hood.</p><p><strong>Difference Between Static and Dynamic Requests</strong></p><p>The HTTP protocol defines the request/response cycle that oversees the data exchange between client and server. This is most evident when we type an address into the address bar and press enter (to send the the request) and watch as the screen flickers as a file object is sent back and rendered. This is called a static request.</p><p>We are also able to make dynamic requests which allow us to update a part of the website without having to reload the whole hog. The object which contains properties and methods that enable us to do this is called XMLHttpRequest.</p><p><strong>Initializing XMLHttpRequest object</strong></p><pre>var xhr = new XMLHttpRequest();</pre><p>What threw me at first when I started working with XMLHttpRequest was thinking that this sent the request straightaway. I had missed the significance of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new">“new” operator</a>, and the fact that the XMLHttpRequest has a duel role of handling the response from the API, as well as sending the request. The above code creates an object which has been pre-populated with certain properties and methods which enable it to handle the server response.</p><p>A property contains data and one of the properties of XMLHttpRequest is XMLHttpRequest.readyState which contains the current state of the XMLHttpRequest object.</p><pre>var xhr = new XMLHttpRequest();</pre><pre>xhr.readyState; // yields 0</pre><p>There are 5 stages (0–4) in the life cycle of the initialized object. In this way we can use XMLHttpRequest.readyState to track the progression of the call, enabling us to execute code in response to a particular status. Once the call is complete the payload from the call will be stored in the property XMLHttpRequest.response whose current value is set to an empty string:</p><pre>xhr.response; // yields &quot;&quot;</pre><p><strong>Initializing the Request</strong></p><p>As well as containing properties the XMLHttpRequest object also contains different methods. XMLHttpRequest.open() is a property of XMLHttpRequest that initializes and configures the request which will subsequently be sent to the server. It sets as a minimum, two parameters:</p><ul><li>HTTP method (i.e. GET/POST etc…)</li><li>URL</li><li>true/false (optional boolean value referring to the method call being synchronous or asynchronous. Default setting is true, which defines the request as asynchronous)</li></ul><p>Using <a href="https://theysaidso.com/api/">They Said So Quotes API</a> I read through the documentation and discovered that if I wanted a JSON object to be returned I need to append .json on to the end of the the URL. Passing in the arguments gives us the following:</p><pre>var xhr = new XMLHttpRequest();</pre><pre>xhr.readyState // yields 0</pre><pre>xhr.open(“GET”, “<a href="http://quotes.rest/qod.json">http://quotes.rest/qod.json</a>”, true)</pre><pre>xhr.readyState // yields 1 </pre><p><strong>Sending the Request to the Server</strong></p><p>Next we use another method, XMLHttpRequest.send(), to actually execute the request. If in the previous step the request was configured as asynchronous the XMLHttpRequest.send() method would return straight away, and the next line of code can be executed. Otherwise, an synchronous request will return only when the full response is sent by the server. The significance of this is that if there was a problem with the response, the user could end up waiting in perpetuity for a response.</p><p>XMLHttpRequest.send()can be passed arguments which make up the <a href="https://stackoverflow.com/questions/22034144/what-does-it-mean-http-request-body">request body</a>, however as we are making a GET request, we can leave it null.</p><pre>var xhr = new XMLHttpRequest();</pre><pre>xhr.readyState // yields 0</pre><pre>xhr.open(“GET”, “<a href="http://quotes.rest/qod.json">http://quotes.rest/qod.json</a>”, true)</pre><pre>xhr.readyState // yields 1</pre><pre>xhr.send(null);</pre><pre>xhr.readyState // yields 2 </pre><p><strong>Response from the Server</strong></p><p>ReadyState 2 indicates that request has received headers from the servers response. Headers contain metadata about the payload which is soon to follow.</p><p>The servers partial response will start to filter in and is stored at the property XMLHttpRequest.responseText. When I tried to test this with the API call it displayed the full data — which I assume is due to the payload in this instance being minuscule and being loaded almost instantaneously. Nevertheless the following code will utilize an <a href="https://stackoverflow.com/questions/2069763/difference-between-event-handlers-and-callbacks">event handler</a> (XMLHttpRequest.onreadystatechange) to console log each state change and accompanying responseText:</p><pre>var xhr = new XMLHttpRequest();<br><br> xhr.onreadystatechange =  function () {<br>   console.log(xhr.readyState);<br>   console.log(xhr.responseText);<br>};</pre><pre>xhr.open(&#39;GET&#39;, &#39;<a href="http://quotes.rest/qod.json&#39;">http://quotes.rest/qod.json&#39;</a>, true); <br>xhr.send(null);</pre><p>The XMLHttpRequest object has several types of <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events">event listener</a>s, that listens for when the xhr.readyState changes. It then calls the assigned function. We can use it in combination with an if statement to run a block of code in event that the server has successfully responded to the API call. It is not sufficient to use xhr.readyState ==4 as a sole condition. This is because it can return 4 (meaning that the API call is finished) even if the call encountered a problem.</p><p>This is where XMLHttpRequest has another property, XMLHttpRequest.status, that is useful. It returns a standard HTTP status code from the server, so in conjunction with XMLHttpRequest.readyState we can check the status of the request from the perspective of the XHR object (XMLHttpRequest.readyStatus) and from the perspective of the server and it’s response(XMLHttpRequest.status).</p><pre>var storeResult = [];<br> function getJSON () {<br>   var xhr = new XMLHttpRequest(); <br> <br>   xhr.onreadystatechange = function () {<br>       if (xhr.status === 200 &amp;&amp; xhr.readyState === 4) {<br>   storeResult.push(JSON.parse(xhr.response));<br>     }<br> else {console.log(&quot;error message&quot;)<br>      }<br> }<br> <br> xhr.open(&quot;GET&quot;, &quot;<a href="http://quotes.rest/qod.json">http://quotes.rest/qod.json</a>&quot;, true);<br> xhr.send(null);<br>};</pre><p>Note that this isn’t the most efficient code in the world. The event handler will fire four times in total (one for each state change), so the else statement will be ran at least three times. Thankfully XMLHttpRequest also includes XMLHttpRequest.onload(), which only triggered once XMLHttpRequest.readyState == 4:</p><pre>var storeResult = [];<br> function getJSON () {<br>   var xhr = new XMLHttpRequest(); <br> <br> xhr.open(&quot;GET&quot;, &quot;<a href="http://quotes.rest/qod.json">http://quotes.rest/qod.json</a>&quot;, true);<br> xhr.send(null);<br> xhr.onload = function () {<br>       if (xhr.status === 200) {<br>   storeResult.push(JSON.parse(xhr.response));<br>     }<br> else {console.log(&quot;error: status is not 200&quot;)<br>      }<br> }<br>};</pre><pre>//Note that we still check the status code of the response</pre><p>The server will respond with the following:</p><pre>&quot;{<br>    &quot;success&quot;: {<br>        &quot;total&quot;: 1<br>    },<br>    &quot;contents&quot;: {<br>        &quot;quotes&quot;: [<br>            {<br>                &quot;quote&quot;: &quot;Sustenance! Your health is always the best prescription.&quot;,<br>                &quot;length&quot;: &quot;56&quot;,<br>                &quot;author&quot;: &quot;Lorii Myers&quot;,<br>                &quot;tags&quot;: [<br>                    &quot;health&quot;,<br>                    &quot;inspire&quot;,<br>                    &quot;sustenance&quot;<br>                ],<br>                &quot;category&quot;: &quot;inspire&quot;,<br>                &quot;date&quot;: &quot;2017-07-27&quot;,<br>                &quot;permalink&quot;: &quot;<a href="https://theysaidso.com/quote/DA1ZF1DwbRwSvLJyHB1IJQeF/lorii-myers-sustenance-your-health-is-always-the-best-prescription">https://theysaidso.com/quote/DA1ZF1DwbRwSvLJyHB1IJQeF/lorii-myers-sustenance-your-health-is-always-the-best-prescription</a>&quot;,<br>                &quot;title&quot;: &quot;Inspiring Quote of the day&quot;,<br>                &quot;background&quot;: &quot;<a href="https://theysaidso.com/img/bgs/man_on_the_mountain.jpg">https://theysaidso.com/img/bgs/man_on_the_mountain.jpg</a>&quot;,<br>                &quot;id&quot;: &quot;DA1ZF1DwbRwSvLJyHB1IJQeF&quot;<br>            }<br>        ],<br>        &quot;copyright&quot;: &quot;2017-19 theysaidso.com&quot;<br>    }<br>}&quot;</pre><p><strong>Same Origin Policy</strong></p><p>The public API for <a href="https://theysaidso.com/api/">They Said So</a> generates a quote of the day. The limitations of this Public API is in its name, it generates a quote of<em> the day. </em>When the user clicks the button multiple times to generate a quote, it will be generating the same quote over and over again.</p><p>However I liked the API for demonstration purposes as it one of the few public quote APIs that does not implement <a href="https://en.wikipedia.org/wiki/Same-origin_policy">same origin policy</a>. All other public APIs that I have came across applies same origin policy. When the above code is run with a different API the following error is returned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*QuytYzhefUFZ8ncBctiJiA.png" /></figure><p>The same origin policy is a basic security measure that help to prohibit a malicious third party website gaining access to information over and above the API call .</p><p>Whilst initially I found it frustrating encountering the above error, in the process of discovering the error I felt I have learnt a lot about the mechanics of making ajax requests. Perhaps you, dear reader, have also learnt something from my efforts too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=973b76ee20d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>