<?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 James Ng on Medium]]></title>
        <description><![CDATA[Stories by James Ng on Medium]]></description>
        <link>https://medium.com/@jng15?source=rss-9788ff9a0a57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*CTMc-W7l0_1NlEt1nGp2PA.jpeg</url>
            <title>Stories by James Ng on Medium</title>
            <link>https://medium.com/@jng15?source=rss-9788ff9a0a57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:02:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jng15/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[Chess-Math to Check-Mate: The Mathematics of Chess]]></title>
            <link>https://jng15.medium.com/chess-math-to-check-mate-the-mathematics-of-chess-2b1ee5eacb18?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b1ee5eacb18</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[chess]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[numbers]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Thu, 01 Feb 2024 00:31:41 GMT</pubDate>
            <atom:updated>2024-02-01T00:31:41.114Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The game of chess was adapted and born out of an Indian game called <a href="https://en.wikipedia.org/wiki/Chaturanga"><em>chaturanga</em></a><em> </em>before the 600s AD. By the end of 19th century, the rules of modern chess were standardized and universally accepted.</p><figure><img alt="Indian game called “chaturanga”. Earliest form of modern chess." src="https://cdn-images-1.medium.com/max/1024/0*jqN2Kqie2SQ58_8s.jpeg" /><figcaption>Antiquated “chaturanga” board.</figcaption></figure><p>Here is a quick overview of the game:</p><ul><li>Two (2) players, white and black. White always goes first.</li><li>Game board consists of 64 squares (8 rows by 8 columns). <em>Learn how to set up the board </em><a href="https://www.chess.com/lessons/how-to-move-the-pieces/setting-up-the-board"><em>here</em></a><em>.</em></li><li>Starting game pieces per player: 8 pawns (♟), 2 rooks (♜), 2 knights (♞), 2 bishops (♝), 1 queen (♛), and 1 king (♚). <em>Learn how each piece moves </em><a href="https://www.chess.com/lessons/how-to-move-the-pieces"><em>here</em></a><em>.</em></li><li>The object of the game is to <strong><em>checkmate</em> </strong>the opponent’s king, meaning to trap him so he cannot make any more moves to avoid capture.</li></ul><figure><img alt="Modern chessboard." src="https://cdn-images-1.medium.com/max/497/1*D0C64qyde0Y1un1wXvSDjQ.png" /><figcaption>Modern chessboard.</figcaption></figure><h3>Chess math</h3><p>What has made chess one of the most popular strategy games for centuries is the mathematics behind the game. All the different combinations of possible moves influence the decision-making process, regarding trade-off and value of each piece.</p><p>Mathematicians, such as Euler and Gauss, and other renowned players have written literature regarding the optimal strategies to play the game, in what is known as <em>chess theory</em>. Chess theory<strong> </strong>divides the game into three phases: <em>opening, middlegame, </em>and <em>endgame.</em></p><p><em>The Oxford Companion to Chess</em> listed 1,327 named opening variations and sub-variations. The picture below shows a glimpse of the decision tree<em> </em>for just a few openings<em>. </em>A <em>decision tree</em> is a math model that uses a tree-like structure to represent different paths (decisions) and outcomes by using “branches”. Think of a family tree or a factor tree.</p><p>Can you try memorizing all of that? 👀</p><figure><img alt="Decision tree of chess openings." src="https://cdn-images-1.medium.com/max/1024/0*uqSMuqUthB52g27M.jpg" /><figcaption>Decision tree of chess openings.</figcaption></figure><p>Each opening is a series of <em>half-moves</em> that each player makes, and results in a different board arrangement each time. A <strong>half-move<em>, </em></strong>also known as a<strong> <em>ply, </em></strong>refers to a move that one player makes. A <strong>move<em> </em></strong>is when both players have moved a piece.</p><p>The table below shows the relationship between the number of half-moves and the number of possible games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*Lulm9WOvGXcd6iwXRrrmCg.png" /><figcaption>Number of half-moves compared to the number of possible games.</figcaption></figure><p>At the start of the game, white has 20 different options for the first ply (<em>16 options for the 8 pawns + 4 options for the 2 knights</em>). Then, black can respond with 20 different options for each move white makes. A quick calculation shows that there are 20 x 20 = 400 different variations of board positions!</p><p>Now, this is where the numbers blow up. In only 10 half-moves (5 full moves), there are <strong>69,352,859,712,417</strong> different possible games that can be played! Mind-blowing 🤯.</p><p>If the table above did not shake your socks off, then look at the graph of the plotted values created on <a href="https://www.desmos.com/calculator/jeeasb9sdt">Desmos</a>. A line of best fit, in the form of an <em>exponential function </em><em>y=a(b)^x, a~0.201, b~28.4, </em>was used as a model to represent this explosion of numbers.</p><figure><img alt="Graph of an exponential line of best fit for the first 10 number of half-moves to the number of possible games." src="https://cdn-images-1.medium.com/max/1024/1*irpCxfJA9vEYptAis8Kh0Q.png" /><figcaption>Line of best fit (exponential) for first 10 half-moves and number of possible games.</figcaption></figure><blockquote><strong><em>Exercise:</em></strong> <em>The average chess game is about 40 full moves, or 80 plies. Based on the line of best fit, try calculating the value y = (0.201)(28.4)⁸⁰. Hopefully, your calculator does not error out!</em></blockquote><h3>Shannon Number</h3><p>In his paper <em>“Programming a Computer for Playing Chess” </em>written in 1950, American mathematician <em>Claude Shannon</em> made an estimate of <strong>10¹²⁰</strong> different game variations in chess. This number was calculated based on a typical game lasting about 40 <em>moves — </em>both white and black take a turn — and that each player can make on average 30 legal moves per turn (ply), approximately 30 x 30 = 900 (about 1000 = 10³) possible variations in one <em>move</em>.</p><blockquote><strong><em>Estimation:</em></strong> <em>(10³)⁴⁰ = 10¹²⁰ different games</em></blockquote><p>Let us attempt to put this number in some sort of context. According to scientists, the number of atoms in the observable universe is roughly 10⁸⁰. Shannon number is about 10¹²⁰ / 10⁸⁰ = 10⁴⁰ greater! 😵 What!?</p><h4>Number of sensible chess games</h4><p>The <a href="https://en.wikipedia.org/wiki/Shannon_number">Shannon number</a> accounts for all possible games, including ridiculous or non-sensical moves that lose games. This is why his number is extraordinary. A more <em>sensible </em>estimate is that a player has about three (3) reasonable moves for each ply (half-move), with the typical game lasting about 40 moves (80 plies). Each move will have about 3 x 3 = 9 (about 10) variations. Thus, the number of <em>sensible </em>games is about <strong>10⁴⁰! </strong>Still a whopping number.</p><figure><img alt="Picture of a man whose mind is boggled." src="https://cdn-images-1.medium.com/max/1024/0*RaQTiTtRgpoZxpaN.jpg" /></figure><h3>Artificial Intelligence (AI)</h3><p>Dr. James Grime pointed out in his <a href="https://www.youtube.com/watch?v=Km024eldY1A">video</a> that <em>“if everyone in the world paired up and played a different game of chess every day to play all possible number of “sensible” games (10⁴⁰), then it will take trillions of years to play them all.”</em></p><p>Put in another way, all the games that have been played in the history of chess is <em>only a fraction</em> of all the possible games that can be played.</p><p>It is virtually impossible for any human to play or conceive of all the possible games in one’s lifetime. This is where <em>artificial intelligence (AI) </em>comes into the scene. AI supercomputers were designed to perform complex calculations and data processing tasks on large amounts of data at high speeds — perfect for something like learning chess.</p><p>In 1996, the world champion of chess Garry Kasparov faced off against IBM’s Deep Blue (AI) computer and won 4–2 in six games. After some upgrades in 1997, <a href="https://theworld.org/stories/2018-01-05/garry-kasparov-and-game-artificial-intelligence">Deep Blue defeated Kasparov</a> in a rematch, 3.5–2.5 (won 2 games, tied 3 games). This marked the first time a computer has defeated a world champion under tournament conditions in a classical match — the dawn of a new era.</p><figure><img alt="Garry Kasparov faces IBM’s Deep Blue (AI) computer in 1997." src="https://cdn-images-1.medium.com/max/937/0*jy7dSVYKZUChZ5EN" /><figcaption>Garry Kasparov vs. Deep Blue (AI) Computer</figcaption></figure><p>Here’s a simple overview of Deep Blue’s <a href="https://stanford.edu/~cpiech/cs221/apps/deepBlue.html">learning techniques</a>:</p><ul><li><strong><em>Tree search </em></strong>🌲🔎 — as discussed earlier with the “decision tree”, the computer searches through each board arrangement (state) and the available legal moves for that state.</li></ul><figure><img alt="Tree searching of different chessboard arrangements." src="https://cdn-images-1.medium.com/max/539/0*oTuUI8dfWp-nxk6g.png" /><figcaption>Sample state (board arrangement) from a tree search.</figcaption></figure><ul><li><strong><em>Evaluation function</em></strong><em> </em>📜💪<em> — </em>a math function that takes a state as an input and returns a score (<a href="https://www.chessprogramming.org/Material">material value</a>) as an output. For the player of interest, it considers all the pieces for both players and assigns a score for the given board arrangement. The higher the number, the greater the likelihood of winning.</li></ul><figure><img alt="Evaluation function for a single state in chess." src="https://cdn-images-1.medium.com/max/450/1*YEn2Mqz9BkVc4DXVps6ILA.png" /><figcaption>Evaluation function.</figcaption></figure><ul><li><strong><em>Minimax algorithm</em></strong><em> </em>📉📈<em>— </em>a series of calculations that attempts to <em>minimize </em>the <em>maximum </em>possible “loss” from making a particular move, given board arrangement. The algorithm will look ahead, as far as the computing power allows, to make such a decision that allows the player of interest to choose the best possible move to increase his/her odds of winning.</li><li><strong><em>Optimization</em></strong><em> </em>⚡⚡<em>— </em>essential technique of cutting out (<em>pruning </em>in computer science lingo) repetitive calculations in a decision tree. For example, it does not make sense to do <em>123 x 321</em> again two minutes and twelve minutes later if the problem was just calculated. The computer can store the result of <em>39,483</em> and reference it for later use. This saves on computing power and processing times.</li></ul><figure><img alt="Optimization of a decision tree." src="https://cdn-images-1.medium.com/max/579/0*KOkq9zG-zMiGQZYc.gif" /><figcaption>Optimization by pruning.</figcaption></figure><p>AI is perfect for handling the sheer amount of possible game variations, numbers, and logical decisions needed to play a game like chess, optimally. Its potential is limitless as computing power, data storage, and algorithms continue to improve each year.</p><p>Phew! Mind-boggling eh? This is just the mathematics of chess. And we have not moved a single piece on the board yet!</p><h3><strong>Summary</strong></h3><ul><li>Claude Shannon estimated the game of chess to have about 10¹²⁰ different possible games, considering all possible legal moves (silly ones too 😅), and about 10⁴⁰ <em>sensible </em>games, considering reasonable (🧠) moves.</li><li>Deep Blue (AI) defeated world champion Garry Kasparov in 1997. It was trained in using learning techniques, such as <em>tree search, evaluation function, minimax algorithm, </em>and <em>optimization.</em></li><li>AI will continue to get better and better at learning as technology continues to improve.</li></ul><h3><strong>References</strong></h3><ul><li><a href="https://www.chess.com/">https://www.chess.com/</a></li><li><a href="https://tomrocksmaths.files.wordpress.com/2021/06/the-mathematics-of-chess-corrected-final-version.pdf">https://tomrocksmaths.files.wordpress.com/2021/06/the-mathematics-of-chess-corrected-final-version.pdf</a></li><li><a href="https://www.chess.com/article/view/history-of-chess#:~:text=Chess%2C%20as%20we%20know%20it,Spanish%20priest%20named%20Ruy%20Lopez">https://www.chess.com/article/view/history-of-chess#:~:text=Chess%2C%20as%20we%20know%20it,Spanish%20priest%20named%20Ruy%20Lopez</a>.</li><li><a href="https://www.linkedin.com/pulse/shared-history-chess-artificial-intelligence-alliance-nigrelli-%E8%83%9C%E8%82%96/">https://www.linkedin.com/pulse/shared-history-chess-artificial-intelligence-alliance-nigrelli-%E8%83%9C%E8%82%96/</a></li><li><a href="https://chess.stackexchange.com/questions/4136/opening-tree-graph">https://chess.stackexchange.com/questions/4136/opening-tree-graph</a></li><li><a href="https://www.livescience.com/how-many-atoms-in-universe.html">https://www.livescience.com/how-many-atoms-in-universe.html</a></li><li><a href="https://stanford.edu/~cpiech/cs221/apps/deepBlue.html">https://stanford.edu/~cpiech/cs221/apps/deepBlue.html</a></li><li><a href="https://enthu.com/blog/chess/number-of-possible-chess-games/">https://enthu.com/blog/chess/number-of-possible-chess-games/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b1ee5eacb18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the Domain Name System(DNS)? How does it work?]]></title>
            <link>https://jng15.medium.com/what-is-the-domain-name-system-dns-how-does-it-work-85f219a2c060?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/85f219a2c060</guid>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[ip]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Fri, 03 Nov 2023 18:17:14 GMT</pubDate>
            <atom:updated>2023-11-03T18:17:14.547Z</atom:updated>
            <content:encoded><![CDATA[<p>Call it the <strong>address book</strong><em> </em>of the internet.</p><p>Let us say you (<em>browser/client) </em>are trying to find a friend (<em>server</em>).</p><p>You first check your contact cards for the address — <em>check browser’s cache</em>. No luck.</p><p>Luckily, there is a service for that! It is called a <strong>DNS Lookup</strong>, which is provided by an<strong> </strong>ISP<strong> </strong>—<em> internet service provider.</em></p><figure><img alt="A schematic of the Domain Name System Lookup process that starts from the client, then to the DNS system, then back to the client, and then to the server." src="https://cdn-images-1.medium.com/max/1024/1*XPbw8MvsJtxJAHo4lfURvA.png" /></figure><p>You go to your ISP for help. The ISP calls upon a local employee called “Messenger” (<strong>DNS recursive resolver</strong><em>)</em> to help with your request to get the address (<strong>IP address</strong>)<em> </em>— after taking your fee of course! 😅</p><p>Messenger loves to work smarter, not harder. He also checks his contact cards (<em>check</em> <em>DNS cache</em>) to see if he has your friend’s information.</p><p>If he has the address, then he will simply give you it. Unfortunately, no luck either! Therefore, he puts on his shoes and gets moving.</p><p>First, Messenger goes to the first department called the <strong>“root nameserver”</strong><em>, </em>with the your friend’s full name.</p><p>The folks there look at your friend’s last name (<em>domain extensions, such as .com, .org, .net</em>) and then direct Messenger to the appropriate building in the second department called the <strong>“TLD (top-level domain) nameserver”</strong>.</p><p>It has two buildings called <em>Generic TLDs </em>and <em>Country Code TLDs:</em></p><ul><li>Generic TLDs have information on people all over the world (<em>ext.— .com, .org, .net, .edu</em>)</li><li>Country Code TLDs have information on local people (<em>ext. — .us, .ru, .ca, .jp</em>)</li></ul><p>The folks in the building direct Messenger to a third department called the “<strong>authoritative nameserver”</strong>. Two things can happen there. The folks can</p><ol><li>Check the database (<strong>DNS A records</strong>)<em> </em>and return with the friend’s address</li><li>Find that your friend goes by another name (<em>alias</em>) in another database (<strong>CNAME records</strong>)<em>.</em></li></ol><p>Messenger prays that they come back with the address or else he would have to go back to the first department and start over again — repeat the DNS Lookup! 😬</p><p>Let us say Messenger gets the address. After a sigh of relief, he returns to you with the address.</p><p>Messenger also makes contact cards with your friend’s information; he gives you one so you do not forget next time and brings another back to office for future reference (<em>store IP address in</em> <em>browser’s cache or DNS infrastructure</em>).</p><p>You go on your way to locate your friend at the address.</p><p>When you guys finally get connected, both of you instantly become chatty!</p><figure><img alt="A schematic that shows an established connection between client and server." src="https://cdn-images-1.medium.com/max/1024/1*lAhMFPcGksJ6HIQJQtsTqA.png" /><figcaption>Established connection between client and server.</figcaption></figure><p><strong>TLDR:</strong></p><ul><li>DNS (Domain Name Server) is the <em>address book</em> of the internet</li><li>When you (<em>browser</em>) try to find a friend (<em>server</em>), your ISP (internet service provider) calls a local Messenger (<em>DNS recursive resolver) </em>to help you find his/her address (<em>IP address)</em></li><li>Messenger wants to work smarter and not harder so he checks his contact cards (<em>cache) </em>to see if he has your friend’s address</li><li>If he does, he will give you the address. If not, then he will visit three different departments (<em>root, TLD, </em>and<em> authoritative </em>nameservers) to help you find the address</li><li>Messenger returns with the address and gives you the contact card for future reference — <em>store IP address in</em> <em>browser’s cache. </em>He also makes note of it himself —<em> store IP address in DNS infrastructure.</em></li><li>You connect with your friend, and start chit-chatting away</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85f219a2c060" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fibonacci Sequence & Golden Ratio: Math in Nature]]></title>
            <link>https://jng15.medium.com/fibonacci-sequence-golden-ratio-math-in-nature-5aaf788f161a?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aaf788f161a</guid>
            <category><![CDATA[nature]]></category>
            <category><![CDATA[universe]]></category>
            <category><![CDATA[golden-ratio]]></category>
            <category><![CDATA[fibonacci]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 01:51:01 GMT</pubDate>
            <atom:updated>2024-02-05T03:12:58.550Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A plant vine, curled in a shape of a spiral, traced by the Golden ratio spiral" src="https://cdn-images-1.medium.com/max/1024/0*mya3hVKeFByDJpAg" /><figcaption>Is the spiral a random occurrence or a grand design?</figcaption></figure><p>You always hear people say “<em>Math is boring!</em>” or ask “<em>What is the point of Math?</em>” You do not have to love or hate Math to <em>appreciate </em>it. Simply put, Math is the science of structure, order, and relation used to make sense of the world around us<em>.</em> If you have ever marveled at nature, then you can at least appreciate Math because there might be some sort of grand design…</p><p>Leonardo Bonacci (Fibonacci), 1170–1250, was an Italian mathematician who was studying the growth of the rabbit population and asked the following question: “How many pairs of rabbits will one pair produce in one year, given that naturally they produce a new pair every month?”</p><p>From his observations, Bonacci came up with the <strong>Fibonacci sequence</strong>, which is <em>1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, …</em><strong>,</strong> etc. It is a simple, math sequence in which each number is the sum of the previous two numbers, starting at 2. The picture below shows this sequence in the formation of tree branches.</p><figure><img alt="Fibonacci sequence in tree branches." src="https://cdn-images-1.medium.com/max/600/1*AweTdetwIuCUlFUbEEEEKg.png" /><figcaption>Fibonacci sequence in tree branches.</figcaption></figure><p>The Fibonacci sequence is significant because of its connection to the <strong>Golden Ratio</strong>, <em>1.618033988749894</em><strong>. </strong>Two quantities <em>a </em>and <em>b </em>are said to be in the Golden Ratio if</p><figure><img alt="Golden ratio equals the sum of a and b divided by a, which also equals a divided by b, where a &gt; b &gt; 0" src="https://cdn-images-1.medium.com/max/135/1*mwSDiJBsHNnJMKRmcf3PwA.gif" /></figure><p>where <em>a &lt; b &lt; 0. </em>The exact value of the ratio is expressed as the Greek Letter φ (<em>phi</em>)<em>,</em></p><figure><img alt="Greek letter phi equals the sum of 1 and the square root of 5, divided by 2." src="https://cdn-images-1.medium.com/max/111/1*ud7tVAP0cKzNMTpQpCB1qA.gif" /></figure><p>Those who are wish to learn more about the calculation of this value can check it out on <a href="https://en.wikipedia.org/wiki/Golden_ratio#Calculation">Wikipedia</a>.</p><p>Notice how the Fibonacci numbers perfectly fit into the Golden Ratio in the schematic below, which forms the <em>Golden rectangle</em>, starting with numbers 1 and 1. A square of side length 2 (sum of 1 and 1) is added to form another rectangle, maintaining the Golden Ratio of <em>a + b </em>and <em>a </em>as each rectangle’s longer side and shorter side, respectively (see image below). From such observation, smart mathematicians were able to draw a logarithmic <em>spiral</em><strong><em> </em></strong>through each square to form the <em>Golden spiral. </em>How golden!</p><figure><img alt="Picture of a spiral that shows the Fibonacci sequence." src="https://cdn-images-1.medium.com/max/828/0*npJb3LwJWSF8rygL" /><figcaption>Gold Spiral with Fibonacci Sequence</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*1f99bIVBpPgzUSsYBlUn3g.png" /><figcaption>Golden Ratio in a rectangle</figcaption></figure><h3>Spirals in Nature</h3><p>Enough with the math. Here comes the cool part!</p><p>If the Golden Ratio is applied as a growth factor in some <a href="https://en.wikipedia.org/wiki/Golden_spiral#Mathematics">math equation</a>, we would get a logarithmic spiral — the Golden spiral. Interestingly, this can be found throughout nature. Here are some examples:</p><figure><img alt="Spirals in botany. Top-left: spiral aloe, bottom-left: flower bud, top-right: seed head, bottom-right: pinecone." src="https://cdn-images-1.medium.com/max/1024/1*AUBiHrkc-_Md36dS9i_ppg.png" /><figcaption>Spirals in botany. Top-left: spiral aloe, bottom-left: flower bud, top-right: seed head, bottom-right: pinecone.</figcaption></figure><figure><img alt="Spirals in nature. Top: ocean wave, bottom-left: hurricane, bottom-right: whirpool." src="https://cdn-images-1.medium.com/max/1024/1*CGB4RODJOU-MUb7hgX2b9A.png" /><figcaption>Spirals in nature. Top: ocean wave, bottom-left: hurricane traced with the spiral, bottom-right: whirpool.</figcaption></figure><figure><img alt="The Golden ratio and spiral traced onto a human face and ear." src="https://cdn-images-1.medium.com/max/1024/1*R4Km3HLhLpxDmnJlOGHUQQ.png" /><figcaption>The Golden ratio and spiral can be traced in a human face and ear.</figcaption></figure><figure><img alt="“The universe is within you.” Left: golden ratio in human hand. Right: gold spiral in a galaxy" src="https://cdn-images-1.medium.com/max/1024/1*nXFrDTckZ2sQ2_jNz66Jpg.png" /><figcaption>Left: Human hand. Wrist and knuckle joints form the Golden ratio. Right: Spiral in a galaxy — approximation.</figcaption></figure><blockquote>Everything in the universe is within you. — Rumi</blockquote><p>It is important to note that these are <em>approximate </em>calculations of the Golden spiral being applied to natural phenomena. Whether you are a believer or non-believer, the patterns appear frequently enough that its significance cannot be understated.</p><p>The Fibonacci sequence and Golden Ratio has captivated mathematicians, artists, designers, and scientists for a long time. Despite the chaotic nature of the universe, this suggests an important characteristic of how nature follows some sort of a blueprint in the grand design of physical matter and attempts to organize it in the most efficient way possible.</p><p>What do you think, random or not?</p><p><strong>References:</strong></p><p><a href="https://en.wikipedia.org/wiki/Fibonacci#Fibonacci_sequence">Fibonacci — Wikipedia</a></p><p><a href="https://en.wikipedia.org/wiki/Golden_ratio">Golden ratio — Wikipedia</a></p><p><a href="https://science.howstuffworks.com/math-concepts/fibonacci-nature.htm#:~:text=Seed%20Heads%2C%20Pinecones%2C%20Fruits%20and%20Vegetables&amp;text=Divide%20the%20spirals%20into%20those,manner%20%5Bsource%3A%20Knott%5D">https://science.howstuffworks.com/math-concepts/fibonacci-nature.htm#:~:text=Seed%20Heads%2C%20Pinecones%2C%20Fruits%20and%20Vegetables&amp;text=Divide%20the%20spirals%20into%20those,manner%20%5Bsource%3A%20Knott%5D</a>.</p><p><a href="https://www.mathnasium.com/blog/14-interesting-examples-of-the-golden-ratio-in-nature">https://www.mathnasium.com/blog/14-interesting-examples-of-the-golden-ratio-in-nature</a></p><p><a href="https://stemettes.org/zine/articles/fibonacci-in-nature/">How Many Times Have You Spotted Fibonacci In Nature? Here Are 7 Examples For You… — The Stemettes Zine</a></p><p><a href="https://www.treehugger.com/how-golden-ratio-manifests-nature-4869736">https://www.treehugger.com/how-golden-ratio-manifests-nature-4869736</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aaf788f161a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Basics IV: Enums, Object Types, and Type Aliases]]></title>
            <link>https://jng15.medium.com/typescript-basics-iv-enums-object-types-and-type-aliases-a9be1dab0a7c?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9be1dab0a7c</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Wed, 30 Nov 2022 16:11:04 GMT</pubDate>
            <atom:updated>2022-11-30T16:11:04.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="TypeScript logo" src="https://cdn-images-1.medium.com/max/700/0*Quwwo4FejFBZbzJt.png" /></figure><p>TypeScript allows for <strong>custom types</strong>, which will allow for <em>greater flexibility to be strict</em> (…sounds ironic 🤔) when writing code. These include <em>enums</em>, <em>object types, type aliases, function types, generic types,</em> and <em>generic functions</em>. This writing will only cover enums, object types, and type aliases and the next post will cover function and generic types.</p><h3>Numeric Enums</h3><p>The complex type <em>enums</em> allows us to <strong>enumerate </strong>all possible values assigned to a variable. For example, the planets of our solar system can be defined as</p><pre>enum Planets { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune };</pre><p>Technically, we can use an array type string[] or tuple type [string, string, …, string] to achieve the same results, but they can be literally anything and therefore be error-prone if we are not careful. For example,</p><pre>let PlanetsArrayType: string[];<br>let PlanetsTupleType: [<br>  string, string, string, string, <br>  string, string, string, string<br>];<br>PlanetsArrayType = [<br>  &#39;Mercury&#39;, &#39;Venus&#39;, &#39;Earth&#39;, &#39;Mars&#39;, <br>  &#39;Jupiter&#39;, &#39;Saturn&#39;, &#39;Uranus&#39;, &quot;🥾 Neptune - PLUTO!&quot;<br>] // or PlanetsTupleType</pre><pre>let planetToExplore = Planets;<br>planetToExplore = Planets.Neptune; // No type error.<br>planetToExplore = Earth; // Error, incorrect syntax. Use Planets.Earth.<br>planetToExplore = Planets.Pluto; /* Error, Pluto is not a valid value <br>for Planets enums */</pre><p>By default, all the values in enum Planets are 0-indexed in the order they appear. In other words,Planets.Mercury = 0 , Planets.Venus = 1 , Planets.Earth = 3 , and so on. Different numbers can be assigned to each value like such:</p><pre>enum Planets {<br>   Mercury=5, Venus=3, Earth=1, Mars=4, <br>   Jupiter=8, Saturn=7, Uranus=2, Neptune=6<br>}<br>let planetToExplore: Planets; //assigns enum Planets to variable<br>planetToExplore = Planets.Mars// No error<br>planetToExplore = 4 // No error, same as above<br>planetToExplore = 1234 // No error but strange....</pre><p>Additionally, a non-zero starting index can be assigned to the first value and TypeScript assigns the rest of the indices incrementally by 1.</p><pre>enum Planets {<br>   Mercury=1, Venus, Earth, Mars, <br>   Jupiter, Saturn, Uranus, Neptune<br>}<br>Planets.Mercury === 1 //true<br>Planets.Earth === 3 //true<br>Planets.Neptune === 7 //false</pre><p>Some practical applications of numeric enums are keeping track of a favorites count or an inventory count for stores. This allows for us to just use the item’s index as opposed to typing out each item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbepOaC_NwlTzpQWhQwdvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*Vuv8CMWDW6ijisnI-6M-4w.png" /></figure><h3>String Enums</h3><p>As we saw in the example above with where the variable planetToExplore can be assigned to any number, such as planetToExplore = 1234, and can lead to bugs and errors. That might be a little too flexible for the strict reputation of TypeScript. <strong>String enums</strong> are generally used in lieu of numeric enums because variables cannot be assigned to arbitrary numbers or strings at all!</p><pre>// Numeric Enum<br>enum PlanetsNum { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune }<br>// String Enum<br>enum PlanetsStr { <br>  Mercury = &#39;MERCURY&#39;, Venus = &#39;VENUS&#39;, Earth = &#39;EARTH&#39;, Mars = &#39;MARS&#39;, <br>  Jupiter = &#39;JUPITER&#39;, Saturn = &#39;SATURN&#39;, Uranus = &#39;URANUS&#39;, Neptune = &#39;NEPTUNE&#39;<br>}</pre><p>Although it seems counterintuitive, string nums <strong><em>do not</em></strong> allow us to assign variables with the string values we defined above. The only valid syntax is the object-key syntax Object.key .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*7A5eGcD1nj5fdG-LahvOmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*D7Zy4aT_HJlSEr0KKMYLOQ.png" /></figure><h3>Object Types</h3><p><em>Object types</em> are the most common of the custom types. They allow for greater control of variable types and data input. Type annotations for objects look like object literals.</p><pre>let dog: { name: string, age: number, breed: string, vaccinated: boolean };</pre><p>When dog is assigned as an object, it<em> </em>must have the name , age, breed, and vaccinated properties of the specific types or else TypeScript will throw errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*RxMk-0StxOfSR6aJ5xiNTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wWM1TvqDtxzOBKxxakmdw.png" /></figure><p>In the example above line 5, the variable dog was assigned values to all properties except for vaccinated, resulting in an error.</p><p>There are no restrictions on assigning types for the object’s properties. For example, the variable myProfile can be assigned the following:</p><pre>let myProfile: {<br>  age: number,<br>  color: string, <br>  favFoods: string[], <br>  friends: { name: string, phone: number }[],<br>  favSuperHero: { name: string, powers: [string, string] },<br>  voted: boolean,<br>  graduated: boolean <br>}</pre><h3>Type Aliases</h3><p>TypeScript allows for <em>type aliases</em>,<em> </em>or arbitrary names that we can choose to assign to types for further customization in our programs. The format is type &lt;alias&gt; = &lt;type&gt; .</p><p>We can refactor the variable myProfile defined earlier by using type aliases like such:</p><pre>type Person = { name: string, phone: number };<br>type SuperHero = { name: string, powers: [string, string] };<br><br>let myProfile: {<br>  age: number,<br>  color: string, <br>  favFoods: string[], <br>  friends: Person[],<br>  favSuperHero: SuperHero,<br>  voted: boolean,<br>  graduated: boolean <br>}<br></pre><p>Furthermore, we can assign the type alias Profile to define the all the properities in myProfile like such:</p><pre>type Person = { name: string, phone: number };<br>type SuperHero = { name: string, powers: [string, string] };<br>type Profile = {<br>  age: number,<br>  color: string, <br>  favFoods: string[], <br>  friends: Person[],<br>  favSuperHero: SuperHero,<br>  voted: boolean,<br>  graduated: boolean<br>}<br><br>let myProfile: Profile = {<br>  age: 23, color: &#39;Blue&#39;, favFoods: [&#39;pizza&#39;, &#39;peanut butter&#39;],<br>  friends: [<br>    { name: &#39;David&#39;, phone: 8001234567 },<br>    { name: &#39;Christina&#39;, phone: 8887654321 }<br>  ],<br>  favSuperHero: { name: &#39;Superman&#39;, powers: [&#39;flying&#39;, &#39;laser&#39;] },<br>  voted: true,<br>  graduated: true<br>}</pre><p>Refactoring with type alias makes our code readable and reusable.</p><h3>Summary</h3><ul><li>Custom types allow for flexibility in TypeScript. Numeric enums assign indices to all possible values assigned to a variable. String enums are stricter in that the proper syntax — Object.key — must be used.</li><li>Object types are most common and take on the form of an object literal. There are no restrictions on assigning types for the properties of the object.</li><li>Type alias are arbitrary names that can be used to further customize our programs, making code more readable and reusable.</li></ul><p><em>Credit &amp; Inspiration: Codecademy’s Learn TypeScript course</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9be1dab0a7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Basics (III): Arrays]]></title>
            <link>https://jng15.medium.com/typescript-basics-iii-arrays-36750905ee15?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/36750905ee15</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Wed, 16 Nov 2022 18:05:16 GMT</pubDate>
            <atom:updated>2022-11-16T18:10:21.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="TypeScript logo" src="https://cdn-images-1.medium.com/max/700/0*gSb11-H2lL-p10t7.png" /></figure><p>Time for the most common data structure to get “typed” up — arrays.</p><p>Type annotation for arrays can be assigned by simply putting a set of square brackets <strong>“[ ]” </strong>after the element type. Another syntax that can be used is <strong>Array&lt;type&gt;</strong>. Here are some examples:</p><pre>let nums1: number[] = [1, 2, 3, 4, 5];<br>let nums2: Array&lt;number&gt; = [6, 7, 8, 9, 10];</pre><p>Once the array is type annotated, TypeScript safeguards against different data types from being associated with it. In the first example, <em>nums </em>is declared as an array type of <em>number </em>and cannot be assigned <em>strings</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*LNHqJmYWQ8ftvs9BTmqflA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*mFVpwKrA4bOxA2hHrj7IEw.png" /></figure><p>Additionally, non-number elements cannot be added to the array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*hfds9P6fa0GDe7VJ5NM1_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*UmJtfO7qlTzAx0rYOTO3IA.png" /></figure><h3>Multi-Dimensional Arrays</h3><p>Multi-dimensional arrays, meaning an array of arrays, can be declared by simply adding another set of square brackets <strong>“[ ]”</strong> to the original syntax.</p><pre>// Notice the double square brackets<br>let nums: number[][] = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; </pre><p>The empty array “[ ]” will not cause errors when assigned to any array type.</p><pre>// No errors for the following:<br>let nums: number[] = [];<br>let strings: string[] = [];<br>let booleans: boolean[] = [];</pre><h3>Tuples</h3><p>Arrays can have multiple data types as elements. A <em>tuple </em>is a data structure with specified length and order of data types for its elements. While there is no default <em>tuple </em>in JavaScript, leave it for TypeScript to “type” it up. Tuple types are annotated with an array of data types in a <em>specific order</em>.</p><pre>/* <br>  tuple of length 4 contains a number, string, boolean, and number<br>  in that order specific order<br>*/<br>let tuple: [number, string, boolean, number] = [ 23, &#39;string&#39;, true, 32 ];</pre><p>TypeScript throws errors when incorrect data types are assigned in the specified order and when the length is not exact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*913BofmrwonUl9WqhET-xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*_yVT6mY3JCWbxcj4bRUp5A.png" /></figure><p>Despite the similarities between tuples and arrays, they are not compatible types in TypeScript. If an array with the same (ordered) data types and length is assigned to a tuple variable, TS will throw a fit. Remember, it is pretty <a href="https://medium.com/@jng15/typescript-basics-type-system-cac2e848b4aa">strict</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*cvGRswNXeLEibBU4W7x00w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*XnMvpdR3xPihnDdR-WO1qg.png" /></figure><h3>Array Type Inference</h3><p>While TypeScript can infer variable types from initial values and return statements, things are slightly different when dealing with arrays. Let’s say we declare a variable <em>nums </em>as the following:</p><pre>let nums = [1, 2, 3];</pre><p>This looks like it could possibly be inferred as an array type<em> number[ ]</em> or tuple type <em>[ number, number, number ]. </em>TypeScript gives the nod to the less restrictive type — the array type. Less restrictive!? 😱</p><pre>let nums = [1,2,3]; // Infers array type: number[]<br>nums[3] = 4; // No error<br>console.log(nums);  //-&gt; [1,2,3,4]</pre><p>Interestingly, TS will infer an array type<em> number[ ]</em><strong> </strong>when the <em>.concat( )</em> method is used on a tuple of numbers.</p><pre>let tuple: [number, number] = [123, 456];<br>let tupleWannaBe = tuple.concat([789]) // Infers array type: number[]<br>console.log(tupleWannaBe) //-&gt; [123, 456, 789]</pre><h3>Rest Parameter &amp; Spread Syntax</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">rest parameter</a> syntax allows for an unlimited number of arguments to be passed in a function. Basically, the “rest of the parameters” are packaged in an array. It is represented with the spread syntax <strong>“…arguments” </strong>and can <strong>ONLY </strong>be the last parameter in a function.</p><pre>// Rest parameter -&gt; ...arguments<br>const function = (a, b, c, ...arguments) =&gt; { code };</pre><p>Since the rest parameter is an array of arguments, then TypeScript allows for type annotation to ensure the right arguments are passed through. A “string” trying to sneak into a “number” party? No funny business!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*mwUQ96BHgrXNGONqyb09Vg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*gWd1YiHdnxv8liqrWv7hbw.png" /></figure><p>Sometimes there are many specific <a href="https://medium.com/@jng15/typescript-basics-ii-functions-2b8ffa30d0a1">argument types passed in a function</a> and it can be quite cumbersome to type out each specific type. For example, the function <em>cakeMaker </em>calls for the following parameters:</p><pre>function cakeMaker(<br>  servingSize: number, <br>  cakeSizeInInches: number,<br>  cakeType: string, <br>  occassion: string, <br>  wantCandles: boolean, <br>  pickUpDay: string<br>) = { code }</pre><p>That is a lot to “type” — no pun intended.</p><p>Instead, we can refactor by using a tuple variable to represent all the specific data types and use the spread syntax to make the code more concise and readable.</p><pre>let cakeDetails: [number, number, string, string, boolean, string] = <br>[ 8, 6, &#39;Strawberry ShortCake&#39;, &#39;birthday&#39;, true, &#39;Saturday&#39; ];<br><br>cakeMaker(...cakeDetails);</pre><h3>Summary</h3><p>Array types can be declared after variable name with a type followed by square bracket “[ ]”, e.g., <em>string[ ] or Array&lt;string&gt;</em>.</p><p>Multi-dimensional array (an array of arrays) types are type annotated with an additional square bracket, e.g., <em>number[ ][ ]</em>.</p><p>Tuple types have specified length and order of data types for its elements, e.g.,<em> [ number, string, boolean ]</em>.</p><p>Array types can be inferred as well. When an array that contains uniform data type is declared ( e.g, <em>let nums = [1,2,3]</em> ), TypeScript infers that it is an array type —<em> number[ ]</em> as opposed to a tuple type — <em>[number, number, number]</em>.</p><p>Rest parameter can be annotated as a specific type with an array type syntax<em>. </em>Spread syntax<em> </em>can be used to refactor code for functions that take in a lot of parameters.</p><p><em>Credit &amp; Inspiration: Codecademy’s Learn TypeScript course</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36750905ee15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Basics (II): Functions]]></title>
            <link>https://jng15.medium.com/typescript-basics-ii-functions-2b8ffa30d0a1?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b8ffa30d0a1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 16:10:23 GMT</pubDate>
            <atom:updated>2022-11-09T16:10:23.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qqy_lYt2MDAAS494.png" /></figure><p>As discussed in <a href="https://jng15.medium.com/typescript-basics-type-system-cac2e848b4aa">TypeScript Basics: Type System</a>, JavaScript allows for flexibility in its domain. Just like the duality of nature, this can be both a good and bad thing. With no security to check the <em>inputs </em>in the front door (parameter), functions may return unwanted results.</p><h3>Parameter Type Annotations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*dud9ELN-h26deOeeLHsHvw.png" /></figure><p>Looks like a problem. Here comes security — TypeScript. In TS, function parameters can be given types just like variables. They can be annotated to “screen” the arguments that are passed in function calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*koZCZhA8dt1AxPYZp7A43w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*JJXZcvi-O9pwWT9vMDf2jA.png" /></figure><p>In the example above, the string <em>“five”</em> is not a number so TS will pick up and bar its function call.</p><h3>Optional &amp; Default Parameters</h3><p>Sometimes in certain use cases for functions, we do not wish to give an argument but still maintain the parameter type. This can be accomplished by simply putting a <strong>“?” </strong>after parameter name and before the semicolon (:).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*bojVdZuHIhrL23YFztoWQA.png" /></figure><p>Running the code above produces,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*edHkRVwnr9ajQBALudRXnw.png" /></figure><p>When a parameter is initialized with a default argument (value), TypeScript will do its magic and assign the default value’s type to be the parameter’s type. This is just like the <em>type inferences</em> we saw for variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*glvYaEPvEmMcBVeROYDwQQ.png" /></figure><p>Running the code above produces,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*pYySSeAf3HyN6yW1ohhpHQ.png" /></figure><p>However, if we input a <em>string, </em>then TS will throw an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*f46IuHiCV7hSUckrsWuDwQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*Al1vapHHody9rhCGilDp-Q.png" /></figure><h3>Return Types</h3><p>Outside security is not enough. There can be trouble brewing inside as well — TypeScript’s got it covered. Again, TS can infer the return type of a function by simply looking at its <em>return</em> statement.</p><p>In this example, the function <em>shouldBeStr() </em>takes in a string argument and returns a string. TS infers that it should return a string. When the variable <em>check </em>is assigned a different data type (<em>e.g., boolean</em>) and tried to set its value to the <em>shouldbeStr(‘yes’)</em>, TS throws an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*FyiqEEGTebEksUXbSy0RRg.png" /></figure><p>TypeScript also allows for <strong>explicit return types </strong>in functions, which can be specified by typing the data type after the “:” trailing the parentheses housing the parameter (red). Explicit return types can also be written using the arrow function syntax (green).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*LJoht4BQwC1eMTPwL3r44A.png" /></figure><p>Both will throw the same errors in line 9. Notice the variable <em>check</em> is assigned a <em>boolean </em>type and is set equal to <em>shouldBeStr(‘yes’)</em>, which was passed a <em>string </em>argument rather than the allowed <em>number </em>argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*zJX7FhHk0QWK7N9JkUOm-w.png" /></figure><p>The <strong>void return type </strong>is used when a function does not return anything. Even though TS will not throw any error if <em>void </em>is not specified, it is customary to specify a return type for functions. Type <em>any</em> can be used in this case as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*5lICLZH28fpeg8o0Assf7Q.png" /></figure><h3>Function Documentation</h3><p>In addition to the JavaScript syntaxes for commenting, such as <strong><em>“// single line”</em></strong> or <strong><em>“/* multi-line */”</em></strong>, TypeScript uses a third type called <em>documentation comments </em>“<strong><em>/** doc comments */</em></strong><em>”, </em>which written directly before a function<strong>. </strong>They are primarily used to provide a brief description of what the function does, its parameters (using <em>@param</em>), and its return value (using <em>@return</em>).</p><pre>/**<br> * DOCUMENTATION COMMENTS FOR FUNCTION NICKNAME<br> * Combines two strings to create a nickname<br> * <br> * @param str1 - The first input string<br> * @param str2 - The second input string<br> * @return String message with nickname<br> *<br> */</pre><pre>function nickName(str1: string, str2: string): string {<br>  return `Your nickname is: ${str1 + str2}`;<br>}</pre><pre>let yourNickName = nickName(&#39;Pizza&#39;, &#39;Lover&#39;)  <br>console.log(yourNickName) //-&gt; &quot;Your nickname is: PizzaLover&quot;</pre><p>If you have done any LeetCode problems in JavaScript, you will notice these documentation comments on top of functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B29mwL2_tWflwJu0TAO5LQ.png" /><figcaption>LeetCode #1: Two Sum</figcaption></figure><p><em>Credit &amp; Inspiration: Codecademy’s Learn TypeScript course</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b8ffa30d0a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript Basics —Type System]]></title>
            <link>https://jng15.medium.com/typescript-basics-type-system-cac2e848b4aa?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/cac2e848b4aa</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Wed, 02 Nov 2022 21:07:26 GMT</pubDate>
            <atom:updated>2022-11-09T16:02:00.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>TypeScript Basics (I)—Type System</h3><h3><strong>Introduction</strong></h3><figure><img alt="TypeScript, src = “https://thenewstack.io/typescript-tutorial-a-guide-to-using-the-programming-language/”" src="https://cdn-images-1.medium.com/max/1024/0*cy5S4LnOIInTBXed.png" /></figure><p><a href="https://www.typescriptlang.org/"><strong>TypeScript (TS)</strong></a><strong> </strong>is JavaScript with syntax for types. It was developed and released by Microsoft in 2012 to provide stricter programming for JavaScript.</p><p>JS allows for great flexibility in its use, but often leads to unexpected behavior and problems at runtime. TS informs developers when a change in a specific area of a program will cause a break in another area through error handling. Pretty neat.</p><p>TypeScript is just JavaScript, but with additional features such as a<em> type system</em> to help catch errors, clarify structure, and refactor code. TS code is written in files with <strong>.ts </strong>extension and is written in a <em>transpiler </em>(converter) that checks for any errors before outputting an almost exact copy in JS format — <strong>.js</strong>. Code is executed using the <strong>tsc</strong> command in the terminal.</p><p>Basically, TypeScript = <strong><em>strict</em></strong><em> </em>and JavaScript = <strong><em>flexible</em></strong>.</p><h3><strong>Type Inferences</strong></h3><p>Recall that JavaScript’s <a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">primitive data types</a> are <em>number, string, boolean, undefined</em>, <em>null</em>, <em>bigint</em>, and <em>symbol. </em>JS allows us to assign any value to any variable, not to mention three different ways to declare one: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var"><em>var</em></a><em>, </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a><em>, </em>and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*F70gIyNQiHbgIM-fbRpYCg.png" /></figure><p>Let’s see what happens when we try to do the same in TS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*VFwRayGZcwPSH5gjVyaLog.png" /></figure><p>We get an error stating that the variable <em>str</em> cannot be assigned a <em>number </em>because it is initialized as a <em>string </em>type data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*YmNc_vZ1CQeUv6Hj7GRaHg.png" /></figure><p>TypeScript expects the data type of the variable to be the same as what it was originally declared. If the <em>str </em>was initially declared as a string “Hello World”, then TS infers that <em>str </em>should <strong>only </strong>be assigned string values. This is called <em>type inference</em>.</p><h3><strong>Type Shapes</strong></h3><p>A data type’s <em>shape </em>refers to the inherent methods and properties of that type. For example, strings have a<em> .length</em> property and <em>.toUpperCase()</em> &amp; <em>.toLowerCase()</em> methods.</p><p>By running the <strong>tsc </strong>command, TS will let you know of any errors associated with the shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*OBs7qNRWNk3jZjqMM2QHNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*owc4pPRsq5BTqvcjxDyM-Q.png" /></figure><p>Notice, the terminal does not only identify the errors, but also gives suggestions as to what it thinks you meant.</p><h3><strong>Type Annotations</strong></h3><p>Variables can have <em>type annotations</em> or type declarations added after their names. Designating a type annotation is simply typing “:” followed by “&lt;data type&gt;”. For example, if we run the following code with the <strong>tsc </strong>command in the terminal,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*YKlEFg1V52-NX-t5iqOXpg.png" /></figure><p>the output would be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*uLtzvTO30EAk5frCjLmiRA.png" /></figure><p>Notice, since we declared that the variable <strong><em>str </em></strong>will be a <em>string</em>, <strong><em>num</em> </strong>will be a <em>number</em>, <strong><em>bool </em></strong>will be a <em>Boolean (true/false)</em>, and <strong><em>empty </em></strong>will be <em>null</em>, TS will expect that those data types (values) are correctly assigned to those variables, respectively. Otherwise, it will throw errors. <strong><em>bool </em></strong>was correctly assigned <strong><em>true </em></strong>so there was no error.</p><p>Lastly, if a variable is declared <em>without </em>being assigned an initial value, TS will not try to infer its data type and will assign it as a type <strong><em>any</em></strong>. This simply means that the variable can be assigned a value of <em>any</em> data type and can be changed at will, unless it was declared by <em>const.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*qjshxhr88EsxfZsw1VkhQg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*q3LQDJyVoMxWZRuor0yo4A.png" /></figure><p><strong>TLDR </strong>— TypeScript is essentially the same as JavaScript, with a few additional features. It enforces <em>strict </em>adherence to a certain set of rules while JS allows for more <em>flexibility </em>in the code but can lead to weird and unwanted behaviors during runtime.</p><p>Think of TypeScript as someone who checks over your work (JavaScript code) before you submit it. Why not, eh?</p><p><em>Credit &amp; Inspiration: Codecademy’s Learn TypeScript course</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cac2e848b4aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to use Props, Children, useContext Hook, and Component Composition in React]]></title>
            <link>https://jng15.medium.com/when-to-use-props-children-usecontext-hook-and-component-composition-in-react-f036cc4974c5?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/f036cc4974c5</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 00:12:43 GMT</pubDate>
            <atom:updated>2022-06-05T00:12:43.960Z</atom:updated>
            <content:encoded><![CDATA[<p>A beauty of React is the ability to make components dynamic through the use of <em>props. </em>Recall that a <em>component</em> is a function that takes props as an argument and returns JSX, which is a language that allows us to directly write HTML in React inside JavaScript files. <strong>Props</strong> contain information that is passed down from the <em>parent</em> component to the <em>child</em> components of the application through an <em>object.</em></p><p>A simple example below shows a Parent component that returns a Child component with props <em>status, food, </em>and<em> number </em>passed down to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WEtnYyHh6-1oUYRzV0uv2A.png" /></figure><p>Additionally, the props can be destructured using <a href="https://www.geeksforgeeks.org/destructuring-of-props-in-reactjs/">object destructuring</a>. Notice what happened after the props was destructured. The status, food, and number were given their own variables and are able to be directly called. This makes code much cleaner and easier to read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRQqgZkbWtz21P_7lwoJhg.png" /></figure><p>Sometimes, there are many components in an application, in which only certain child components need access to the props. The application can contain a nested structure like this example where data is initially grabbed from the <em>App </em>component, through importing data, fetching, etc. In this case, the <em>Form </em>and <em>CardInfo</em> components both need access the <em>data prop</em> so the parent component <em>App</em> passes the <em>data prop</em> all the way down to those components. This is commonly known as <strong>prop-drilling</strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*BjrBtc84PguISXqSBWa5Cg.png" /></figure><p>Prop drilling is fine in a small application like this one, but can be cumbersome when dealing with large applications that are heavily nested. To solve this issue, the React Hook called <a href="https://reactjs.org/docs/hooks-reference.html#usecontext"><strong>“useContext”</strong></a><strong> </strong>is used. Simply put, the <em>useContext </em>hook allows us to directly pass a prop to all the components that need it without having to prop drill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*q3CpUJuGVGit_1QVLXBD8w.png" /></figure><p>React Context requires two things:</p><ol><li>Context object — object that contains useful data and/or stateful info. <em>(Think internet or cable service).</em></li><li>A context provider component — “provides the context”, or useful info. <em>(Think internet or cable service provider).</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZwIBTi9KTNjkJ4GLL1-Xg.png" /></figure><p>Finally, we just need to import “useContext” hook from the React library to be able to use context and call our context object using ‘useContext( )’ in our target components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*2HJnsdt2DMWS2DOfiRwq7Q.png" /></figure><p>And there you have it! React Context allows us to easily pass useful (stateful as well) information directly to specific components without having to play ‘hot-potato’ with a prop!</p><p>However, there is a something to be cautious about when using context. Let us say we created a new component in our application called <em>About, </em>which contains the <em>CardInfo</em> component as well<em>. </em>Although <em>CardInfo </em>received ‘context’ because it is a child of the Container component, which is wrapped by the <em>DataProvider </em>tag in the <em>App </em>component, running the app will throw an error because the <em>CardInfo </em>child component of <em>About </em>is ‘out of context’ (not wrapped inside the context provider tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpWIRQwjEuEtBs_dXafTow.png" /></figure><p>This is analogous to Javascript concept of scoping issues. You can read more about scope in Javascript <a href="https://www.w3schools.com/js/js_scope.asp">here</a>.</p><p>React documentation states to use context sparingly,</p><blockquote>Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse <strong>more difficult.</strong></blockquote><blockquote>If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context. — <a href="https://reactjs.org/docs/context.html#before-you-use-context">Before You Use Context</a></blockquote><p><strong>Component composition</strong> makes use of the <em>children prop</em> to eliminate prop drilling in our example, without the need for context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYI60aquq7ZLeCrCriceZw.png" /></figure><p>As Michael Jackson puts it in his <a href="https://www.youtube.com/watch?v=3XaXKiXtNjw">video</a>, useContext is <em>implicit </em>while props and children are <em>explicit</em>, which avoids complexity and issues such as a component being <em>out of context</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f036cc4974c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Recursion?]]></title>
            <link>https://jng15.medium.com/what-is-recursion-8baa40f2359?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/8baa40f2359</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[blog]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Sat, 14 May 2022 15:49:41 GMT</pubDate>
            <atom:updated>2022-05-14T15:49:41.630Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Recursion </strong>is the process in which a function invokes itself again. In other words, it repeats the same action(s). Think of a live actor who repeats the same act show after show to a different audience each time until the last showtime.</p><p>In programming, a recursive function calls itself over and over again until a certain condition is satisfied. The syntax for a recursive function is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*tLYrHvipaE60qBiC86zRZA.jpeg" /></figure><p>Let us take a look at an example of how it works. The following function recurse(<em>n</em>) takes a single number <em>n</em> and applies the recursion concept by adding up all the numbers that decrement by 1 until the function reaches 1, the condition that ends the function. This condition will be discussed further at the end of this read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*3q_wipp-mtUxWC9kI60_8g.jpeg" /></figure><p>In this case, the number (<em>argument</em>) n=10 is passed into the function. The computer tests the <em>if</em> statements and finds that the <em>else if </em>statement is true, hence it returns <em>10 + recurse(9)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*CNmR5EA0o0AgLoZsJ3NzFA.jpeg" /><figcaption>***FOR ILLUSTRATION PURPOSES. NOT ACTUAL SYNTAX***</figcaption></figure><p>In <em>recurse(9)</em>, n = 9 is passed through as an argument this time and the function is invoked (ran) again. Again, the computer tests the <em>if</em> statements returns the value of the true statement: <em>9 + recurse(8). </em>Hopefully, you can see how the process repeats itself for n = 7, 6, 5, 4, 3, 2, 1 <em>until</em> the condition of n=1 is met.</p><p>Let us take a look at what is happening in the function towards the end, particularly when n=2 and n=1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*jnHmF4srj5RcUAMODkCn1w.jpeg" /><figcaption>***FOR ILLUSTRATION PURPOSES ONLY. NOT ACTUAL SYNTAX***</figcaption></figure><p>When n=1, the function recurse(1) is ran once more. This time, n=1 satisfies the first condition in the if statements (1 == 1) so the computer will return the value of <em>1 </em>and stops executing the function here. <em>Remember, once a condition is satisfied in one of multiple if statements (starting from top down), the computer stops executing there.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*f4-5isTSo_H1FF3nfFL65w.jpeg" /></figure><p>Therefore, the final result of running the recurse function for n=10 is <strong><em>55</em></strong><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8baa40f2359" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Be Content In An Unhappy Society]]></title>
            <link>https://jng15.medium.com/how-to-be-content-in-an-unhappy-society-e03b34be5875?source=rss-9788ff9a0a57------2</link>
            <guid isPermaLink="false">https://medium.com/p/e03b34be5875</guid>
            <category><![CDATA[self-love]]></category>
            <category><![CDATA[content]]></category>
            <category><![CDATA[peace]]></category>
            <category><![CDATA[money]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[James Ng]]></dc:creator>
            <pubDate>Mon, 22 Feb 2021 22:02:18 GMT</pubDate>
            <atom:updated>2021-02-22T22:02:18.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://pixabay.com/illustrations/smilies-emoticons-especially-1607163/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JmzgzPbTxwlE4bdGuNdIcw.jpeg" /></a></figure><p>Imagine you had one million dollars.</p><p>Think about all the things that you can buy! A new house, a flashy car, expensive clothing, eating at fancy restaurants, VIP services, etc. You can finally enjoy life, and it would be great without a budget. You will not have to worry anything — life would be amazing!</p><p>The age-old question is can material things bring you happiness? Can you be content with what you have, whether it is $1,000,000 or $100? While there is nothing wrong with having and spending money as it is a necessary part of life, problems arise when you are <em>not </em>content with what you have. Discontentment usually results from comparing yourself to others, which consequently creates feelings of inadequacy.</p><p>Buddhism teaches that the source of unhappiness is desire — which is true in the ideal sense. No desires mean no expectations, no expectations mean no disappointments, and no disappointments mean no unhappiness. However, most people do not live in that mental plane to contemplate giving up on their desires and passions. People need to live with a sense of purpose and are moved by ideas, desires, and aspirations.</p><p>Being content can be difficult because society promotes an “ideal life” for people to strive towards—one that usually focuses on material goods and luxurious comfort, which is supported by lots of money. You see others doing this, having that, and you want it too.</p><p>The challenge is to learn how and when to be content with your current state.</p><p>Leo Babauta of <a href="https://zenhabits.net/">Zen Habits</a> said that “contentment is a superpower”, and talked about the necessary skills for contentment:</p><p>1. <strong>Awareness.</strong> Notice when you are making comparisons when you have ideals, fantasies, and expectations, especially when they are making you less content and causing pain.</p><p>2. <strong>Acceptance.</strong> Do not beat yourself up about it and accept that this process is happening. It is part of life. Change what you cannot accept and accept what you cannot change.</p><p>3. <strong>Letting Go of Comparisons.</strong> When you notice the comparisons, accept that you have made them but realize that they are hurting you, and that they are completely unnecessary. You can let go of them and be perfectly fine.</p><p>4. <strong>Compassion.</strong> Compassion for yourself — this is how you let go of the ideals and comparisons. They are hurting you and making you less happy. It is a compassionate act to let go of them. Let them be.</p><p>5. <strong>Appreciation. </strong>Instead of comparing and holding onto ideals, focus instead on appreciating what you have, who you are with, what you are doing, and who you are. Find the good in each thing, including yourself.</p><p>6. <strong>Loving yourself, and everything else too.</strong> Once you have found the good to appreciate in yourself or anything/anybody around you, learn to love it. This is the beauty of life and it is incredible.</p><p>— adapted from the <em>Little Book of Contentment</em> by Leo Babauta</p><figure><a href="https://unsplash.com/photos/70H8nM0Uels"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QzEEHhZfE9hu0W5JnhriGw.jpeg" /></a></figure><p>Sometimes, you do not know why you are doing what you are doing because you were told or forced to do it at a time when you were not mentally matured yet. Other times, you are aware of what are you doing but are motivated for the wrong reasons — jealousy, outdoing your competition, showing off, making ego statements, etc.</p><p>Strive for a certain goal in your <strong><em>own</em></strong> terms and be content with whatever happens when you have done the best you could.</p><p>Learn to be content so that you do not get caught up with comparisons and expectations that take away from your happiness and peace.</p><p>Be mindful to act towards others in a meaningful way that empowers and encourages growth instead of a demeaning way that creates resentment, jealousy, or other <a href="https://jng15.medium.com/become-negative-about-negativity-1a8acca71094?sk=da75905c078187641537391d7fad695f">negative</a> feelings.</p><blockquote>“When you are content with simply being yourself</blockquote><blockquote>And don’t compare or compete,</blockquote><blockquote>Everybody will respect you.</blockquote><blockquote>Fill your bowl to the brim,</blockquote><blockquote>And it will spill.</blockquote><blockquote>Keep sharpening your knife,</blockquote><blockquote>And it will blunt.</blockquote><blockquote>Chase after money and security,</blockquote><blockquote>And your heart will never unclench.</blockquote><blockquote>Care about people’s approval,</blockquote><blockquote>And you will be forever their prisoner.</blockquote><blockquote>Do your work, then step back.</blockquote><blockquote>The only path to serenity.”</blockquote><p><em>—</em> excerpt from<em> Tao Te Ching</em> by Lao Tzu<em> (translated by Stephen Mitchell)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e03b34be5875" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>