<?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 Andrew Ogaga on Medium]]></title>
        <description><![CDATA[Stories by Andrew Ogaga on Medium]]></description>
        <link>https://medium.com/@andyogaga?source=rss-c6f92b03eea8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1up3rQ3vy-YKHcx1Bj3Sww.jpeg</url>
            <title>Stories by Andrew Ogaga on Medium</title>
            <link>https://medium.com/@andyogaga?source=rss-c6f92b03eea8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:02:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andyogaga/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[Why we NEVER MUTATE STATE in React Javascript]]></title>
            <link>https://andyogaga.medium.com/why-we-never-mutate-state-in-react-javascript-73e35b779cea?source=rss-c6f92b03eea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/73e35b779cea</guid>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[mutation]]></category>
            <dc:creator><![CDATA[Andrew Ogaga]]></dc:creator>
            <pubDate>Sat, 17 Oct 2020 12:38:17 GMT</pubDate>
            <atom:updated>2020-10-17T12:47:39.397Z</atom:updated>
            <content:encoded><![CDATA[<p>We have always accepted not to directly mutate the state in React, be it local state within the components or the redux state with regards to reducers. Have you given thought to <strong><em>why</em></strong> that is? This article will try to improve our knowledge on why state mutation is a taboo if you dont want to have buggy code in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlGue60DYnHxStE41cP6JA.jpeg" /><figcaption>Why we dont mutate state in react js — Andrew Ogaga</figcaption></figure><p>First of all, lets understand some basic concepts regarding Javascript data types.</p><h3><strong>Primitive Data Types:</strong></h3><p>There are <strong><em>5 primitive data type</em></strong>s in Javascript which are Strings, Numbers, Booleans, Nulls, and Undefined and these are passed by value when being copied or reassigned. This means that a new space in memory is created for each value being reassigned. See example below.</p><pre>let a = &quot;obinna&quot;;<br>let b = a;<br>console.log(a) --&gt; &quot;obinna&quot;<br>console.log(b) --&gt; &quot;obinna&quot;</pre><p>It means that a was assigned a memory space and b was also assigned a memory space based on their values and a change in value of a will not affect the value of b. See below for example.</p><pre>let a = &quot;obinna&quot;;<br>let b = a;<br>a = &quot;segun&quot;;<br>console.log(a) --&gt; &quot;segun&quot;<br>console.log(b) --&gt; &quot;obinna&quot;</pre><p>From illustration above we will notice that a change in a had no effect on b.</p><h3>Non-primitive data types</h3><p>Some examples of non-primitive data types are Objects, Functions and Arrays. These types of data are passed by reference and this will be explained below.</p><pre>let original = {value: &quot;ahmed&quot;}<br>let copied = original;<br>console.log(original) --&gt; {value: &quot;ahmed&quot;}<br>console.log(copied) --&gt; {value: &quot;ahmed&quot;}</pre><p>If we decide to mutate the object original by changing the value of original.value, we notice that copied.value will also change.</p><pre>let original = {value: &quot;ahmed&quot;}<br>let copied = original;<br>original.value = &quot;moses&quot;;</pre><pre>console.log(original) --&gt; {value: &quot;moses&quot;}<br>console.log(copied) --&gt; {value: &quot;moses&quot;}</pre><p>This behaviour is seen because of the way in which Javascript saves their non-primitive values to variables. The values to be saved to memory are saved, the address to that location in memory is also saved and finally, all variables are referenced to the address in location.</p><p>So in this case where the object original is reassigned to a new variable copied, it does not recreate a new address in memory nor does it create a new object in memory. What it does is to reference the new variable copied to the same object in memory. Hence, a change in any of the variables original or copied will effectively change the value in memory which will be seen by both copied and original. Isnt that interesting?</p><p>More details can be found in a <a href="https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0">very good article by Arnav Aggarwal</a></p><h3>So what does this all have to do with immutability in React?</h3><p>So, <a href="https://reactjs.org/">React </a>as a JS framework rerenders its components if the props or the state of that component changes. In this article, we will be making use of <a href="https://reactjs.org/docs/hooks-intro.html">React hooks</a> to illustrate our example while making use of an object as the the initial state (as seen in the useState below) to correctly illustrate effect of mutating a state.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Example() {<br>const [name, setName] = useState({name: &#39;Aisha&#39;}});<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;You changed the Name to {name.name}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setName({name: &#39;Wale&#39;})}&gt;<br>        Change name<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>From example above, we notice that the state name changes by making use of setName function produced by the hook useState. Consequently, if the name changes after the button click, the component rerenders to show the new name <strong><em>Wale.</em></strong></p><p>One might be tempted to change the state of name by doing so:</p><pre>name.name = &#39;Wale&#39;;</pre><p>Technically, this is one way of changing the property of a <strong><em>Javascript object</em></strong> but in the case of <strong>React</strong>, this is not advised as the address of the variable name is not changed. It changes the value of name.name in memory but as react does not notice a change in the address of the memory, it does not recognize it as a change. Hence, the component is not rerendered.</p><p>If we rerender that component by any other means (correctly changing state or props), its rerender will show that the value has been changed and will display <strong><em>Wale</em></strong>.</p><p>This could cause a bug in your codebase and will be very very hard to track so its strongly advised to make use of setState in <strong>Class based components</strong> and the setter of useState in React hooks.</p><blockquote><strong><em>I will love to see contributions in the comments section on how this article can be improved or any question regarding this so we can learn together.</em></strong></blockquote><p>Thanks Guys.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73e35b779cea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analyzing How to generate Prime Numbers in Javascript]]></title>
            <link>https://andyogaga.medium.com/analyzing-how-to-generate-prime-numbers-in-javascript-b1eccd92ca91?source=rss-c6f92b03eea8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1eccd92ca91</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[prime-numbers]]></category>
            <category><![CDATA[sieve-of-eratosthenes]]></category>
            <category><![CDATA[andrew-ogaga]]></category>
            <dc:creator><![CDATA[Andrew Ogaga]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 07:46:34 GMT</pubDate>
            <atom:updated>2020-10-14T16:09:16.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*SB7wLXlGOJHQznUu5IFGjQ.jpeg" /><figcaption>algorithm to generate prime numbers</figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Prime_number">Prime numbers</a> are numbers that are divisible by only one and itself. This feature makes them unique as they are mostly used in modern cryptography for security. To this end, its generation is quite necessary. There are different methods of generating prime numbers and these methods can be applied in different methods.</p><p>These methods do the job but at a slow rate and takes a lot of memory (i.e. they have very <a href="https://yourbasic.org/algorithms/big-o-notation-explained/">high space and time complexities</a>). I plan on analyzing some effective ways of generating first <strong><em>n</em></strong> prime numbers where <strong><em>n</em></strong> is a chosen number of integers in Javascript.</p><h3><strong><em>Checking all numbers if they are prime until exact number is gotten.</em></strong></h3><p>This involves checking all the numbers between 2 and <strong><em>n</em></strong> to confirm if they are prime numbers. This can be gotten as follows.</p><pre>const checkIfPrime = (num) =&gt; {<br> for (var i = 2; i &lt; num; i++) {<br>  if (num % i === 0) {<br>   return false;<br>  }<br> }<br> return true;<br>};</pre><pre>const generatePrimeNumbers = (noOfPrimes = 10) =&gt; {<br> let workingArray = [2];<br> // Returns the number of primes needed when we reach that limit<br> if (noOfPrimes &lt; workingArray.length) {<br>  return workingArray.slice(0, noOfPrimes);<br> }<br> // Checks for prime for only odd numbers after 3 or last value of gotten primes.<br> for ( let i = 2;<br>  workingArray.length &lt; noOfPrimes;<br>  i ++ ) {<br>   if (checkIfPrime(i)) {<br>    workingArray.push(i);<br>   }<br> }<br> return workingArray;<br>};</pre><p>The code above first checks if a given number is a prime number by checking if it is divisible by any number below it. To throw more light, if you wish to check if 7is a prime, it will check if it is divisible by 2, if true, then it is not a prime, if false, iteration occurs and it tries for 3 until it gets to 6 at which it still isn’t divisible, hence it is a prime.</p><p>In terms of time and space complexity, the <a href="https://www.studytonight.com/data-structures/time-complexity-of-algorithms">time complexity</a> is around O(m*n) and a <a href="https://www.studytonight.com/data-structures/space-complexity-of-algorithms">linear space complexity</a>. This works but it very slow and could take too much CPU load hence the need for a better solution.</p><h3>Changing the top limit to check its factors.</h3><p>To illustrate this point, let us see the illustration of all the factors of 36.</p><pre>2 x 18<br>3 x 12<br>4 x 9<br><strong>6 x 6  ---&gt; Mid line<br></strong>9 x 4<br>12 x 3<br>18 x 2</pre><p>If you look closely at the factors of the number 36 and try to replicate this for other numbers, you will notice that the factors of a number are totally replicated after the square root of that number. This will help greatly in reducing the number of times that we check the factors of a particular number as we will use the upper limit as the square root of the number as seen below.</p><pre>const checkIfPrime = (num) =&gt; {<br> for (var i = 2; i &lt; Math.ceil(sqrt(num)); i++) {<br>  if (num % i === 0) {<br>   return false;<br>  }<br> }<br> return true;<br>};<br><strong>… Code follows</strong></pre><p>In terms of time and space complexity, the <a href="https://www.studytonight.com/data-structures/time-complexity-of-algorithms">time complexity</a> is around O(m*LogN) because the square root makes n become LogN and a <a href="https://www.studytonight.com/data-structures/space-complexity-of-algorithms">linear space complexity</a>. This greatly reduces the amount of mathematically computations to be made but it can still be better.</p><h3>Skip checks for even numbers</h3><p>We all know that even numbers are numbers that are divisible by 2 and you would have noticed that as we iterate, we also iterated over 2 too, hence multiples of 2 was also checked. Lets take that out by tweaking the start limit and step as follows:</p><pre>const checkIfPrime = (num) =&gt; {<br> if (num === 2) return true; <br> for (var i = 3; i &lt;Math.ceil(sqrt(num)); i+= 2) {<br>  if (num % i === 0) {<br>   return false;<br>  }<br> }<br> return true;<br>};<br><strong>… Code follows</strong></pre><p>From the little tweak seen there, we return 2 if we are testing for 2, but from 3 upwards, we iterate of over steps of 2. For example, while checking if 51 is prime, we check 2, 3, 5, 7 and return false if they are factors and return true if they aren’t.</p><p>This is the fastest we have now but it can still be faster by reducing the possible number of iterations for larger numbers.</p><h3><strong>Skip Check for multiples of primes</strong></h3><p>This method was pointed out by a friend of mine <a href="https://medium.com/u/51146f971fa3">Daniel Adepoju</a>. Thanks Bro.</p><p>If we decide to check if 101 is a prime, the square root would be 10.01… but the Math.ceil(101) would be 11, hence we are to check if 3, 5, 7, 9 are factors else it is a prime.</p><p>Looking closely, you would notice that 3 is a factor of 9 hence it is most definitely divisible by 3, so 9 should also be skipped. If we decide to do this for larger numbers, we will notice that we only have to check if the number <strong><em>n</em></strong> is divisible by primes. Hence, we need to find a way to pass only the previous primes to this function. See as follows:</p><pre>const checkIfPrime = (num) =&gt; {<br> if (num === 2) return true;<br>  for (let i = 3; i &lt;Math.ceil(sqrt(num)); I += 2) {<br>   if (num % i === 0) {<br>    return false;<br>   }<br>  }<br> return true;<br>};</pre><pre>const generatePrimeNumbers = (noOfPrimes = 10, lastArr = []) =&gt; {<br> let workingArray = [2];<br> // Replace working array with latest array of primes<br> if (Array.isArray(lastArr) &amp;&amp; lastArr.length &gt; 1) {<br>  workingArray = lastArr;<br> }<br> // Returns the number of primes needed when we reach that limit</pre><pre> if (Array.isArray(lastArr) &amp;&amp; noOfPrimes &lt; lastArr.length) {<br>   return lastArr.slice(0, noOfPrimes);<br> }<br> // Checks for prime for only odd numbers after 3 or last value of gotten primes.</pre><pre> for (<br>  let i = workingArray.length === 1 ? 3 : workingArray[workingArray.length - 1] + 2;<br>  workingArray.length &lt; noOfPrimes;<br>  i += 2) {<br>   if (checkIfPrime(i, workingArray)) { <br>     workingArray.push(i);<br>   }<br> }<br> return workingArray;<br>};</pre><p>We have used logic to greatly increase our computation speed and we have accomplished a great feat. This can also be tweaked by making use of closures so it can remember the last state of the prime number list. Most likely this could be implemented if you need to frequently check first <strong><em>n </em></strong>primes from user input.</p><p>We could still go one step further to greatly increase our computation speed by using the Sieve of Eratosthenes.</p><h3>Sieve of Eratosthenes</h3><p>This is a mathematical way of generating primes introduced by <strong><em>Eratosthenes of Cyrene</em></strong> dated around 276 BC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*ZCDjSI5Qnc4Xah6VfqB_9Q.gif" /><figcaption>Sieve of Eratosthenes</figcaption></figure><p>The image above helps you understand how exactly this is done. While we have been checking if a particular number is prime, the <a href="https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes"><em>Sieve of Eratosthenes</em></a><em> </em>looks to check which numbers are prime within a given range by crossing out multiples of that number until that particular range is covered.</p><p>For example, to get the primes between 0 and 20, we start from 2 which is a prime and cancel out multiples of 2 which become <em>composites (numbers that are not prime)</em>. These composites are 4, 6, 8, 12, 14, 16, 18. Then we move to 3 multiples of 3 are 6, 9, 12, 15, 18; multiples of 4 are 8, 12, 16 and finally multiples of 5 (which is Math.ceil(20)) are 10, 15.</p><p>Looking closely, we would notice that 2, 3, 5, 7, 11, 13, 17, 19 are not multiples of any number, hence they are prime numbers. This greatly increases the speed of computation especially when you wish to get primes within a large range.</p><p>Since we want to get the first <strong><em>n</em></strong> prime numbers, the trick is to take a calculated guess on the possible number of primes that can be gotten from a particular max range, generate the primes within that range and return only the number of primes you need.</p><p>This can be gotten as follows.</p><pre>const checkPrimeWithSoE = (primesNeededString = 10) =&gt; {<br> return new Promise((resolve) =&gt; {<br>  const primesNeeded = Number(primesNeededString);<br>  if (primesNeeded &lt; 1) return []; <br>  // Returns an empty array if primes is less than 1</pre><pre>  if (primesNeeded === 1) return [2]; <br>  // Returns only 2 as prime if one is needed</pre><pre>  if (primesNeeded === 2) return [2, 3]; <br>  // Returns 2, 3 as only primes if only two are needed.</pre><pre>  // Generates an array of indices from 0 to maximum range (square of then number of primes needed) and populates it with true to show that at the beginning all numbers are primes.</pre><pre>  const primeArrayMap = new Array(primesNeeded *  primesNeeded).fill(true);</pre><pre> // We loop through the numbers and change their values for multiples of all numbers till the number of primes needed.</pre><pre>  let i = 2;<br>  while (i &lt;= primesNeeded) {<br>   if (primeArrayMap[i]) {<br>    for ( let multiple = i * i;<br>     multiple &lt; primeArrayMap.length; <br>     multiple += i ) {<br>       primeArrayMap[multiple] = false;<br>    }<br>   }<br>   i++;<br>  }<br>  <br>// We resolve the promise with the indices of the true values as they are the only numbers that arent multiples of numbers</pre><pre>// The array is sliced to get the exact number of prime numbers we need.</pre><pre>  resolve(<br>   primeArrayMap.map((prime, i) =&gt; {<br>    if (prime) return i;<br>    return undefined;<br>   }).filter(Boolean).slice(1, primesNeeded + 1));<br> });<br>};</pre><p>In the function above, we took a calculated guess that the number of primes we need will always be gotten from the square of that number of primes. For example, if you need 10 primes, it will always be gotten from range of 0–100. 50 primes can always be gotten from range of 0–2500 etc.</p><p>In terms of time complexity, this method is far better as it has a Big O of</p><p>O(Nlog(logN))</p><p>Where N is the maximum range to get the primes. This shows that this method is the fastest amonth those mentioned.</p><p>It also has its caveat as in terms of Space complexity, it is very high due to the amount of data it saves while generating the primes</p><h3>CONCLUSION</h3><p>While we have continually found ways of making the generation of primes faster by efficiently checking if a particular number is a prime to generating a list of prime numbers for a particular range, they are not without their demerits.</p><p>The constant check for primes takes time and computation power due to the number of times it checks if a number has factors. The sieve method is computationally faster but takes too much space for large numbers as it has to generate an array of large lengths to which some computers might not be able to handle.</p><p>To this end, we will be looking into some better ways of generating prime numbers in articles to come.</p><blockquote><strong><em>Stay tuned.</em></strong></blockquote><blockquote>PS. I will love to see your reviews and constructive criticism so I could improve this.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1eccd92ca91" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>