<?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 Grant Ferowich on Medium]]></title>
        <description><![CDATA[Stories by Grant Ferowich on Medium]]></description>
        <link>https://medium.com/@gferowich?source=rss-c09f73e554df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BigF_XdCWLwxiaYT487MeA.jpeg</url>
            <title>Stories by Grant Ferowich on Medium</title>
            <link>https://medium.com/@gferowich?source=rss-c09f73e554df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:39:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gferowich/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[How to Build a Binary Search Tree Class (JavaScript and C++)]]></title>
            <link>https://medium.com/@gferowich/how-to-build-a-binary-search-tree-class-javascript-and-c-af90fca62ad0?source=rss-c09f73e554df------2</link>
            <guid isPermaLink="false">https://medium.com/p/af90fca62ad0</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Grant Ferowich]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 20:01:46 GMT</pubDate>
            <atom:updated>2023-11-30T18:19:34.672Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><p>What’s a binary search tree? A binary search tree (BST) is a type of graph with nodes, a root node, and pointers (also called directed edges) which connect the nodes. So, a BST is made of nodes. Each node has an integer value. You probably won’t see a binary search tree comprised of strings. The whole point of the binary search tree is to maintain the binary search tree invariant, which we will cover later. You have probably seen a binary search tree before but if you haven’t here is what every binary search tree looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*tKqRpVIAAgrey1hliynifg.png" /></figure><p>The BST invariant is a statement which must always be true about a tree in order for the tree to be a BST. For any node, the node value to the left of the node must be less than the current node’s value. The node value to the right of the current node value must be greater than the current node value.</p><p>The BST invariant is important to remember because the invariant determines how to traverse the BST in search of a particular value, like when we want to read information about the BST. Similarly, when we want to create nodes and append them to the BST, we will only insert a node to the left of a certain node when there is space to add a node and the insertion node’s value is less than a certain node’s value. We will only insert a node to the right of a certain node when there is space to add a node and the insertion node’s value is greater than a certain node’s value. Whether we are creating, reading, updating, or deleting a node from a BST the BST invariant must always be maintained.</p><p>Why is a BST called what it is? Each node points to two other nodes at most. Since there are only two nodes which a given node points at the tree structure is called a binary tree. If a given node pointed to a maximum of four nodes, we would call the tree something else (a quadtree). So, by learning about binary search trees, you are also learning about binary trees. Binary trees are similar to binary search trees except there is no particular invariant applied to normal binary trees. Knowing about binary trees is great, because min heaps and max heaps are binary trees.</p><p>Keep in mind a BST is not the same thing as a binary search algorithm. Binary search refers to starting at the middle of an array, making a comparison, and then cutting the array in half again, looking at the middle point of the shortened array, making a comparison, and cutting the array in half again. A basic binary search algorithm chops the array in half over an over again until a value is found. What’s similar about the binary search algorithm and the BST is the time complexities associated with the binary search algorithm and certain operations. Searching for a value in an array with a binary search algorithm has a runtime of O(log(N)).</p><p>Searching for a value within a BST has a runtime of O(log(N)) if the BST is balanced. Inserting a value within a BST also has a runtime of O(log(n)) if the BST is balanced. Whether or not a BST is balanced is determined by whether or not the insertion and find operations have runtimes of O(log(N)). The nodes which have no child nodes are called leaves. For perfect BSTs where all nodes except the leaves have two child nodes and all of the leaves are on the same level the insert and find methods have runtimes of O(log(N)).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBDBR-MxlEMDeGaw9ZyLwA.png" /><figcaption>A balanced, perfect BST</figcaption></figure><p>If the BST is unbalanced, searching for a value in a BST has a runtime of O(N).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DoDPlQuS0yZ_p336igyivw.png" /><figcaption>A very unbalanced BST</figcaption></figure><p>BSTs and binary trees are also types of graphs. Any time you see a data structure with nodes connected to one another you are looking at a graph. Graphs are technically non-linear data structures. By contrast, arrays, stacks, queues, and strings are all linear data structures.</p><p>What’s the point in differentiating linear and non-linear data structures? With stacks, queues, arrays, linked lists, and strings, traversing the data structure takes linear time. With non-linear data structures, i.e. graphs, there may not be a clear start and end to the data structure. Binary trees, binary search trees, and heaps all have root nodes. Not all graphs have root nodes, however. Here’s an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*NbcLLQgZJkuo3lZLihoOnw.png" /><figcaption>A graph.</figcaption></figure><p>Now that we have covered the basics of the BST we can move onto the implementations.</p><p><strong>JavaScript:</strong></p><pre><br>class TreeNode{<br>    constructor(valueInt){<br>        this.valueInt = valueInt === undefined ? null : valueInt;<br>        this.rightInt = null;<br>        this.leftInt = null;<br>    }<br>}<br><br>class BinarySearchTree{<br>    constructor(){<br>        this.rootInt = null;<br>        this.sizeInt = 0;<br>    }<br><br>    // time complexity: O(N)<br>    // input: int<br>    // output: undefined<br>    insert(valueInt){<br>        let insertionNodeInt = new TreeNode(valueInt)<br>        if (this.sizeInt === 0){<br>            this.rootInt = insertionNodeInt;<br>            this.sizeInt++;<br>            return;<br>        }<br><br>        const traverse = (nodeInt) =&gt; {<br><br>            if (valueInt &lt;= nodeInt.valueInt &amp;&amp; nodeInt.leftInt === null){<br>                nodeInt.leftInt = insertionNodeInt;<br>                this.sizeInt++<br>                return;<br>            }<br><br>            if (valueInt &gt; nodeInt.valueInt &amp;&amp; nodeInt.rightInt === null){<br>                nodeInt.rightInt = insertionNodeInt;<br>                this.sizeInt++;<br>                return <br>            }<br>            <br>            if (valueInt &gt; nodeInt.valueInt){<br>                traverse(nodeInt.rightInt);<br>            }<br>            if (valueInt &lt; nodeInt.valueInt){<br>                traverse(nodeInt.leftInt);<br>            }<br>        }<br><br>        traverse(this.rootInt)<br>    }<br><br>    // run time: O(N)<br>    // input: int<br>    // outout: true or false<br>    search(valueInt){<br>        if (valueInt === null &amp;&amp; this.rootInt === null){<br>            return true<br>        }<br><br>        const traverse = (nodeInt) =&gt; {<br>        <br>            // destination<br>            if (nodeInt.valueInt === valueInt){<br>                return true;<br>            }<br><br>            // recursive case 1<br>            if (valueInt &lt;= nodeInt.valueInt &amp;&amp; nodeInt.leftInt !== null){<br>                return traverse(nodeInt.leftInt);<br>            }<br><br>            // recursive case 2<br>            if (valueInt &gt; nodeInt.valueInt &amp;&amp; nodeInt.rightInt !== null){<br>                return traverse(nodeInt.rightInt);<br>            }<br>        }<br>        return traverse(this.rootInt) !== undefined ? true : false<br>    }<br>}</pre><p><strong>C++:</strong></p><pre><br>#include &lt;typeinfo&gt;<br>#include &lt;iostream&gt;<br>using namespace std;<br><br>class TreeNode {<br>  public:<br>    int valueInt;<br>    TreeNode *leftNode;<br>    TreeNode *rightNode;<br><br>    TreeNode(int inputInt) {<br>      this-&gt;valueInt = inputInt;<br>      this-&gt;leftNode = nullptr;<br>      this-&gt;rightNode = nullptr;<br>    }<br>};<br><br>class BinarySearchTree {<br>  public:<br>    TreeNode *rootNode;<br>    int sizeInt;<br><br>    BinarySearchTree() {<br>      this-&gt;rootNode =  nullptr;<br>      this-&gt;sizeInt = 0;<br>    }<br><br>    // Time Complexity: O(N)<br>    // Auxiliary Space Complexity: O(1)<br>    void traverseAndInsert(TreeNode *insertionNode,TreeNode *node){<br>        if (insertionNode-&gt;valueInt &lt; node-&gt;valueInt &amp;&amp; node-&gt;leftNode == nullptr){<br>            node-&gt;leftNode = insertionNode;<br>            this-&gt;sizeInt++;<br>            return;<br>        }<br>        if (insertionNode-&gt;valueInt &gt; node-&gt;valueInt &amp;&amp; node-&gt;rightNode == nullptr){<br>            node-&gt;rightNode = insertionNode;<br>            this-&gt;sizeInt++;<br>            return;<br>        }<br>        if (insertionNode-&gt;valueInt &lt; node-&gt;valueInt){<br>            traverseAndInsert(insertionNode, node-&gt;leftNode);<br>        } else {<br>            traverseAndInsert(insertionNode, node-&gt;rightNode);<br>        }<br>    }<br><br>    // Time Complexity: O(N)<br>    // Auxiliary Space Complexity: O(1)<br>    void insert(int valueInt) {<br>        TreeNode *xNode = new TreeNode(valueInt);<br>        TreeNode *node = this-&gt;rootNode;<br>        if (sizeInt == 0){<br>            this-&gt;rootNode = xNode;<br>            this-&gt;sizeInt++;<br>            return;<br>        } <br>        traverseAndInsert(xNode, node);<br>    }<br><br>    // Time Complexity: O(N)<br>    // Auxiliary Space Complexity: O(1)<br>    bool traverseAndSearch(int searchInt, TreeNode *node){<br>            if (node == nullptr){<br>                return false;<br>            }<br>            if (searchInt == node-&gt;valueInt){<br>                return true;<br>            }<br>            bool leftToF = traverseAndSearch(searchInt, node-&gt;leftNode);<br>            bool rightToF = traverseAndSearch(searchInt, node-&gt;rightNode);<br>            return leftToF || rightToF;<br>    }<br><br>    // Time Complexity: O(log(N))<br>    // Auxiliary Space Complexity: O(1)<br>    bool search(int valueInt) {<br>        TreeNode *node = this-&gt;rootNode;<br>        bool resultToF = traverseAndSearch(valueInt, node);<br>        return resultToF;<br>    }<br>};<br><br>void printInOrder(TreeNode *node, const string&amp; positionStr) {<br>        if (node == nullptr) {<br>            return;<br>        }<br>        printInOrder(node-&gt;leftNode, &quot;Left: &quot;);<br>        cout &lt;&lt; positionStr &lt;&lt; node-&gt;valueInt &lt;&lt; &quot;. &quot; &lt;&lt; endl;<br>        printInOrder(node-&gt;rightNode, &quot;Right: &quot;);<br>};</pre><p>I hope you have an amazing time on your coding journey!</p><p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af90fca62ad0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use CoinGecko’s Free API to Calculate the ROI of a Short Position]]></title>
            <link>https://medium.com/coinmonks/how-to-use-coingeckos-free-api-to-calculate-roi-of-a-short-position-2db5f6f5b294?source=rss-c09f73e554df------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db5f6f5b294</guid>
            <category><![CDATA[coingecko]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Grant Ferowich]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 13:27:56 GMT</pubDate>
            <atom:updated>2023-11-30T18:20:15.926Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><p>Are you looking to buy the CoinGecko Annual API subscription <a href="http://coingecko.com/api">here</a>? Use referral code CGGRANT to get $500 off the Annual API subscription purchase.</p><p>Suppose you shorted 1 Bitcoin on January 1, 2023 and you want to find the return on investment programmatically. This post is for you.</p><p>In my <a href="https://medium.com/@gferowich/generating-the-roi-of-a-long-position-with-coingeckos-api-step-by-step-8733e90918be">last post</a>, I covered how to programmatically determine the return on investment of a long position with CoinGecko’s free <a href="https://www.coingecko.com/en/api/documentation">application programming interface</a> (API). In this post, I will show you how to calculate the ROI of a short position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25HakKXotJ_n_X0rcMIfQg.png" /><figcaption>CoinGecko’s API has been useful for making financial calculations</figcaption></figure><p>A short position is a position in which the position value increases when the price of the underlying asset falls. Suppose you shorted 1 Bitcoin on January 1, 2023 and you want to find the return on investment programmatically. This post is for you.</p><p>In the previous exercise, you may have observed you can calculate the ROI of a position with just a few pieces of information:</p><ul><li>The quantity of the asset.</li><li>The initial date on which the short position was opened.</li><li>The API symbol associated with the asset you care about</li></ul><p>You will also need the API key associated with the asset you want information about. You can go to the /coins/list endpoint of the <a href="https://www.coingecko.com/en/api/documentation">CoinGecko API</a> to find the <em>symbol</em> associated with the asset you care about. For Bitcoin, the symbol is “bitcoin.”</p><p>Just as with the calculation of the long position ROI, we start out by calculating the <em>initial position value. </em>On January 1, 2023, the price of Bitcoin was $16,540.69. Let’s suppose that the short position consists of selling short 1 Bitcoin. The initial position value is $16,540.69.</p><pre>const calculateInitialPositionInt = async (APISymbolStr, quantityInt ,indexDateStr) =&gt; {     <br>    let historicalPriceAPIStr = &quot;https://api.coingecko.com/api/v3/coins/&quot;+APISymbolStr+&quot;/history?date=&quot;+indexDateStr+&quot;&amp;localization=false&quot;;<br>    let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) =&gt; response.data.market_data.current_price.usd);<br>    let initialPositionValueInt = historicalPriceInt * quantityInt;<br>    return initialPositionValueInt.toFixed(2);<br>}</pre><p>Next, we will calculate how much the position changed in value. Again, we need the API symbol, the quantity of the asset shorted (1), and the date on which the position was initiated (“01–01–2023”). To find the difference, we take the present price less the historical price on January 1, 2023, multiply by the quantity (1), and multiply by -1 since we are interested in the short position.</p><pre>const calculateDifferenceInt = async (APISymbolStr, quantityInt, indexDateStr) =&gt; {<br>    let historicalPriceAPIStr = &quot;https://api.coingecko.com/api/v3/coins/&quot;+APISymbolStr+&quot;/history?date=&quot;+indexDateStr+&quot;&amp;localization=false&quot;;<br>    let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) =&gt; response.data.market_data.current_price.usd);<br>    let presentPriceAPIStr = &quot;https://api.coingecko.com/api/v3/simple/price?ids=&quot;+APISymbolStr+&quot;&amp;vs_currencies=usd&quot;;<br>    let presentPriceInt = await axios.get(presentPriceAPIStr).then((response) =&gt; response.data[APISymbolStr].usd); <br>    let differenceInt = -1 * (presentPriceInt - historicalPriceInt) * quantityInt;<br>    return differenceInt.toFixed(2)<br>}</pre><p>To make the percentage calculation, we need to determine the present position value. We will do that next. We simply combine the current position value with the difference value. If the difference value is positive, the position has increased in value. If the difference value is negative, the position has decreased in value.</p><pre>const calculatePresentPositionInt = (initialPositionValueInt, differenceInt) =&gt; {<br>    let currentPositionInt = parseFloat(initialPositionValueInt) + parseFloat(differenceInt)<br>    return currentPositionInt.toFixed(2)<br>}</pre><p>Next, we will calculate the ROI in percentage point terms.</p><pre>const calculatePercentageROIInt = (initialInt, presentInt) =&gt; {<br>    let percentageInt = ((presentInt - initialInt) / initialInt) * 100;<br>    return percentageInt.toFixed(2)<br>}</pre><p>Finally, let’s tie everything together. Notice that by writing with JavaScript here we make use of the async/await syntax. The async/await syntax basically just means the function will <em>wait</em> until an API call is completed before the next line of code is executed. Also note that whenever you want to use async/await inside of a function, the entire function must be an async function.</p><pre>// Developed August 28, 2023 <br>// file is called roiShort.js<br>const axios = require(&#39;axios&#39;);<br>// inputs: api key string, asset quantity, and index date<br>// output: $ value of the position <br>const calculateInitialPositionInt = async (APISymbolStr, quantityInt ,indexDateStr) =&gt; {     <br>    let historicalPriceAPIStr = &quot;https://api.coingecko.com/api/v3/coins/&quot;+APISymbolStr+&quot;/history?date=&quot;+indexDateStr+&quot;&amp;localization=false&quot;;<br>    let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) =&gt; response.data.market_data.current_price.usd);<br>    let initialPositionValueInt = historicalPriceInt * quantityInt;<br>    return initialPositionValueInt.toFixed(2);<br>}<br><br>const calculateDifferenceInt = async (APISymbolStr, quantityInt, indexDateStr) =&gt; {<br>    let historicalPriceAPIStr = &quot;https://api.coingecko.com/api/v3/coins/&quot;+APISymbolStr+&quot;/history?date=&quot;+indexDateStr+&quot;&amp;localization=false&quot;;<br>    let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) =&gt; response.data.market_data.current_price.usd);<br>    let presentPriceAPIStr = &quot;https://api.coingecko.com/api/v3/simple/price?ids=&quot;+APISymbolStr+&quot;&amp;vs_currencies=usd&quot;;<br>    let presentPriceInt = await axios.get(presentPriceAPIStr).then((response) =&gt; response.data[APISymbolStr].usd); <br>    let differenceInt = -1 * (presentPriceInt - historicalPriceInt) * quantityInt;<br>    return differenceInt.toFixed(2)<br>}<br><br>const calculatePresentPositionInt = (initialPositionValueInt, differenceInt) =&gt; {<br>    let currentPositionInt = parseFloat(initialPositionValueInt) + parseFloat(differenceInt)<br>    return currentPositionInt.toFixed(2)<br>}   <br><br>const calculatePercentageROIInt = (initialInt, presentInt) =&gt; {<br>    let percentageInt = ((presentInt - initialInt) / initialInt) * 100;<br>    return percentageInt.toFixed(2)<br>}<br><br>const callFunctions = async () =&gt; {<br>    const initialBitcoinPositionValueInt = await calculateInitialPositionInt(&quot;bitcoin&quot;, 1, &quot;01-01-2023&quot;);<br>    console.log(&quot;Intial Bitcoin position value: $&quot;, initialBitcoinPositionValueInt);<br>    const differenceBetweenInitialAndCurrentInt = await calculateDifferenceInt(&quot;bitcoin&quot;, 1, &quot;01-01-2023&quot;)<br>    console.log(&quot;Difference between initial position and current position in $:&quot;, differenceBetweenInitialAndCurrentInt);<br>    const presentPositionInt = calculatePresentPositionInt(initialBitcoinPositionValueInt, differenceBetweenInitialAndCurrentInt);<br>    console.log(&quot;Present Bitcoin position value: $&quot;, presentPositionInt)<br>    const percentageROIInt = calculatePercentageROIInt(initialBitcoinPositionValueInt, presentPositionInt);<br>    console.log(&quot;ROI in % terms:&quot;, percentageROIInt)<br>}<br><br>callFunctions();</pre><p>The resulting output from this script is the following:</p><pre>Intial Bitcoin position value: $ 16540.69<br>Difference between initial position and current position in $: -9453.31<br>Present Bitcoin position value: $ 7087.38<br>ROI in % terms: -57.15</pre><p>Boom! There you have it. The ROI of a short position on Bitcoin in 2023 is -57.15%. The ROI is negative because the price of Bitcoin has increased. If the price of Bitcoin had decreased, the ROI on the short position would be position.</p><p><strong>Also, read:</strong></p><ul><li><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></li><li><a href="https://medium.com/@gferowich/generating-the-roi-of-a-long-position-with-coingeckos-api-step-by-step-8733e90918be"><strong><em>How to Use CoinGecko’s Free API to Calculate the ROI of a Long Position: Step-by-step</em></strong></a></li><li><a href="https://medium.com/coinmonks/how-to-use-coingeckos-free-api-to-get-digital-asset-data-just-the-basics-d46f232926cb"><strong><em>How to Use CoinGecko’s Free API to Get Digital Asset Data: Just the Basics</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db5f6f5b294" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-use-coingeckos-free-api-to-calculate-roi-of-a-short-position-2db5f6f5b294">How to Use CoinGecko’s Free API to Calculate the ROI of a Short Position</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use CoinGecko’s Free API to Calculate the ROI of a Long Position: Step-by-step]]></title>
            <link>https://medium.com/coinmonks/generating-the-roi-of-a-long-position-with-coingeckos-api-step-by-step-8733e90918be?source=rss-c09f73e554df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8733e90918be</guid>
            <category><![CDATA[coingecko]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Grant Ferowich]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 18:40:36 GMT</pubDate>
            <atom:updated>2023-11-30T18:20:45.581Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><p>Are you looking to buy the CoinGecko Annual API subscription <a href="http://coingecko.com/api">here</a>? Use referral code CGGRANT to get $500 off your Annual API subscription purchase.</p><p>Suppose you bought 1 Bitcoin on January 1, 2023 and you want to find out the return on investment (ROI) programmatically. This guide is for you.</p><p>CoinGecko has an awesome API. I have used CoinGecko’s API in an application for making financial calculations. Today, I will show you how you can also calculate the performance of a long position position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*25HakKXotJ_n_X0rcMIfQg.png" /><figcaption>CoinGecko’s API has been helpful for me</figcaption></figure><p>Let’s quickly review some basics. A long position consists of you buying some asset. If you are long, your position appreciates when the price of the asset increases. In this article, I will go over the calculation of the return on investment (ROI) of a long position.</p><p>Now, let’s move on to the programmatic approach. Let’s start with the input information. To determine the ROI of a long or short position we need the following information:</p><ul><li>the quantity of the asset</li><li>the initial date on which you purchased the asset</li></ul><p>Suppose you bought 1 Bitcoin on January 1, 2023 and you want to find out the ROI programmatically. With just the quantity of the asset and the initial date, we can use CoinGecko’s API and some math skills to output the ROI.</p><p>We can break down the process into smaller steps. First, we want to know the <em>initial position value</em> in dollars. Secondly, we want to know the <em>current position value. </em>Finally, we can calculate the ROI as a percentage by doing: (Current position value — initial position value) / initial position value. So, just to develop intuition and to provide an example, if I had one Bitcoin at a price of $10,000, the initial position value would be $10,000. Suppose the price increased to $20,000. The current position value would be $20,000. ($20,000 — $10,000) / $10,000 returns 1, which, in percentage point terms, is 100%.</p><p>Here’s what a script looks like for calculating the initial position value programmatically.</p><pre>const axios = require(&#39;axios&#39;);<br>// inputs: api key string, asset quantity, and index date<br>// output: $ value of the position <br>const calculateInitialPositionInt = async (APISymbolStr, quantityInt ,indexDateStr) =&gt; {     <br>    let historicalPriceAPIStr = &quot;https://api.coingecko.com/api/v3/coins/&quot;+APISymbolStr+&quot;/history?date=&quot;+indexDateStr+&quot;&amp;localization=false&quot;;<br>    let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) =&gt; response.data.market_data.current_price.usd);<br>    let initialPositionValueInt = historicalPriceInt * quantityInt;<br>    return initialPositionValueInt;<br>}<br><br>const callFunction = async () =&gt; {<br>    const initialBitcoinPositionValueInt = await calculateInitialPositionInt(&quot;bitcoin&quot;, 1, &quot;01-01-2023&quot;)<br>    console.log(&#39;Intial Bitcoin position value: $&#39;, initialBitcoinPositionValueInt);<br>}<br>callFunction();</pre><p>Now, let’s add in the function to calculate the present position value:</p><pre>const calculatePresentPositionInt = async (APISymbolStr, quantityInt) =&gt; {<br>    let presentPriceAPIStr = &quot;https://api.coingecko.com/api/v3/simple/price?ids=&quot;+APISymbolStr+&quot;&amp;vs_currencies=usd&quot;;<br>    let presentPriceInt = await axios.get(presentPriceAPIStr).then((response) =&gt; response.data[APISymbolStr].usd); <br>    let presentPositionValueInt = presentPriceInt * quantityInt;<br>    return presentPositionValueInt;<br>}</pre><p>Lastly, let’s calculate the return on investment in percentage point terms.</p><pre>const calculatePercentageROIInt = (initialInt, presentInt) =&gt; {<br>    return ((presentInt - initialInt)/ initialInt) * 100<br>}</pre><p>Now, let’s put it all together!</p><pre>// file is called calculateRoi.js<br>const axios = require(&#39;axios&#39;);<br>// inputs: api key string, asset quantity, and index date<br>// output: $ value of the position <br>const calculateInitialPositionInt = async (APISymbolStr, quantityInt ,indexDateStr) =&gt; {     <br>    let historicalPriceAPIStr = &quot;https://api.coingecko.com/api/v3/coins/&quot;+APISymbolStr+&quot;/history?date=&quot;+indexDateStr+&quot;&amp;localization=false&quot;;<br>    let historicalPriceInt = await axios.get(historicalPriceAPIStr).then((response) =&gt; response.data.market_data.current_price.usd);<br>    let initialPositionValueInt = parseInt(historicalPriceInt * quantityInt);<br>    return initialPositionValueInt;<br>}<br><br>const calculatePresentPositionInt = async (APISymbolStr, quantityInt) =&gt; {<br>    let presentPriceAPIStr = &quot;https://api.coingecko.com/api/v3/simple/price?ids=&quot;+APISymbolStr+&quot;&amp;vs_currencies=usd&quot;;<br>    let presentPriceInt = await axios.get(presentPriceAPIStr).then((response) =&gt; response.data[APISymbolStr].usd); <br>    let presentPositionValueInt = presentPriceInt * quantityInt;<br>    return presentPositionValueInt;<br>}<br><br>const calculatePercentageROIInt = (initialInt, presentInt) =&gt; {<br>    return ((presentInt - initialInt)/ initialInt) * 100<br>}<br><br>const callFunctions = async () =&gt; {<br>    const initialBitcoinPositionValueInt = await calculateInitialPositionInt(&quot;bitcoin&quot;, 1, &quot;01-01-2023&quot;)<br>    console.log(&quot;Intial Bitcoin position value: $&quot;, initialBitcoinPositionValueInt);<br>    const presentBasketValueInt = await calculatePresentPositionInt(&quot;bitcoin&quot;, 1);<br>    console.log(&quot;Present Bitcoin position value: $&quot;, presentBasketValueInt)<br>    const percentageROIInt = calculatePercentageROIInt(initialBitcoinPositionValueInt, presentBasketValueInt);<br>    console.log(&quot;ROI in percentage terms:&quot; ,percentageROIInt)<br>}<br><br><br>callFunctions();</pre><p>The script prints out the following output to the console:</p><pre>Intial Bitcoin position value: $ 16540<br>Present Bitcoin position value: $ 25904<br>ROI in percentage terms: 56.614268440145096</pre><p>Boom! Purchasing 1 Bitcoin on January 01, 2023 resulted in a 56.61% ROI as of August 26, 2023.</p><p><strong>Also, read:</strong></p><ul><li><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></li><li><a href="https://medium.com/@gferowich/how-to-use-coingeckos-free-api-to-calculate-roi-of-a-short-position-2db5f6f5b294"><strong><em>How to Use CoinGecko’s Free API to Calculate the ROI of a Short Position</em></strong></a></li><li><a href="https://medium.com/coinmonks/how-to-use-coingeckos-free-api-to-get-digital-asset-data-just-the-basics-d46f232926cb"><strong><em>How to Use CoinGecko’s Free API to Get Digital Asset Data: Just the Basics</em></strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8733e90918be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/generating-the-roi-of-a-long-position-with-coingeckos-api-step-by-step-8733e90918be">How to Use CoinGecko’s Free API to Calculate the ROI of a Long Position: Step-by-step</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving LeetCode 209 Efficiently: Your Roadmap to Minimum Size Subarray Sum (Medium)]]></title>
            <link>https://medium.com/@gferowich/solving-leetcode-209-efficiently-your-roadmap-to-minimum-size-subarray-sum-medium-14e9a13be4fe?source=rss-c09f73e554df------2</link>
            <guid isPermaLink="false">https://medium.com/p/14e9a13be4fe</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Grant Ferowich]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 16:50:12 GMT</pubDate>
            <atom:updated>2023-11-30T18:21:17.049Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><p>A guide for conquering a dynamically-sized sliding window problem efficiently.</p><p>Hello to all my fellows navigating the path through data structures and algorithms. Today we will be walking through a sliding window problem where the size of the window is dynamic. In the previous post, I described a method for thinking about sliding window problems and provided a 6-step approach for solving any sliding window problem. You can view the post here: <a href="https://medium.com/@gferowich/tutorial-on-leetcode-239-sliding-window-maximum-hard-26a90285325b">https://medium.com/@gferowich/tutorial-on-leetcode-239-sliding-window-maximum-hard-26a90285325b</a>. The section called “Methodological approach to solving sliding window problems” introduces the 6-step approach.</p><p>Sliding windows are linear data structures which satisfy some invariant. In <a href="https://leetcode.com/problems/minimum-size-subarray-sum/description/">LeetCode 209. “Minimum Size Subarray”</a> the question asks us to find the smallest subarray which has numbers whose sum is greater than or equal to an input integer called the target integer. In cases where there are multiple subarrays whose digits sum to a number greater than or equal to the target integer, the function is expected to return the smallest such subarray.</p><p>I proposed solving sliding window problems by answering the following questions. Creating a visual diagram is another great way to really own the problem.</p><ol><li>Does the question ask me to implement a fixed-sized sliding window or a dynamically-sized sliding window?</li></ol><ul><li>A dynamically-sized sliding window.</li></ul><p>2. Under what condition does the right pointer move?</p><ul><li>When the sum of the current subarray is less than the target integer.</li></ul><p>3. When will the function read the temporary solution?</p><ul><li>When the sum of the current subarray is greater than or equal to the target integer.</li></ul><p>4. How will the function decide on the optimal solution?</p><ul><li>The optimal solution is the subarray with the fewest number of digits whose digits sum to a sufficient value.</li></ul><p>5. Under what condition does the left pointer move?</p><ul><li>The left pointer moves when the sum of the current subarray is greater than or equal to the target integer.</li></ul><p>6. Which category does the SWP fall under?</p><ul><li>Fast/slow.</li></ul><pre>const minimumSizeSubarraySum = (target, nums) =&gt; {<br>    <br>    let rightPtrInt = 0;<br>    let leftPtrInt = 0;<br>    let sumInt = 0<br>    let lengthInt = Infinity<br><br>    while (sumInt &lt; target){<br>        let rChar = nums[rightPtrInt];<br>        sumInt += rChar;<br>        rightPtrInt++;<br>        while (sumInt &gt;= target){<br>            if (rightPtrInt - leftPtrInt &lt; lengthInt){<br>                lengthInt = rightPtrInt - leftPtrInt;<br>            }<br>            let lChar = nums[leftPtrInt];<br>            sumInt -= lChar;<br>            leftPtrInt++;<br>        }<br>    }<br>    return lengthInt === Infinity ? 0 : lengthInt;<br>}<br><br><br>/* TESTS */<br><br><br>let test1 = minimumSizeSubarraySum( 7, [2,3,1,2,4,3])<br>console.log(&#39;Test 1:&#39;, test1)<br>// Expected output: 2<br><br>let test2 = minimumSizeSubarraySum( 4, [1,4,4])<br>console.log(&#39;Test 2:&#39;, test2)<br>// Expected output: 1<br><br>let test3 = minimumSizeSubarraySum( 11, [1,1,1,1,1,1,1,1])<br>console.log(&#39;Test 3:&#39;, test3)<br>// Expected output: 0<br><br>let test4 = minimumSizeSubarraySum(11, [1,2,3,4,5])<br>console.log(&#39;Test 4&#39;, test4)<br>// Expected output: 3</pre><p>The time complexity of this function is O(N). The function finds the optimal subarray after one loop through the array. The auxiliary space complexity of the function is O(1). No matter how large the input grows there are only four integer variables associated with the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0aBU7GpoJaZhM7TUdAgkoQ.png" /></figure><p>I hope you have an amazing rest of your day and enjoy your journey through data structures and algorithms!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14e9a13be4fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial on LeetCode 239. Sliding Window Maximum (Hard)]]></title>
            <link>https://medium.com/@gferowich/tutorial-on-leetcode-239-sliding-window-maximum-hard-26a90285325b?source=rss-c09f73e554df------2</link>
            <guid isPermaLink="false">https://medium.com/p/26a90285325b</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Grant Ferowich]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 11:18:14 GMT</pubDate>
            <atom:updated>2023-11-30T18:26:08.276Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><p>This post is for people solving sliding window problems during their LeetCode journeys.</p><ol><li>Recognizing sliding window problems</li><li>Methodological approach to solving sliding window problems</li><li>The approach for 239. “Sliding Window Maximum”</li><li>Time and space complexities</li><li>Edge case</li><li>A note on the type of linear data structure in the input: array or string</li><li>Softly typed JavaScript</li></ol><p><em>Recognizing sliding window problems</em></p><p>Sliding window problems (SWPs) are a relatively common problem category you will see during interviews. The main idea with a sliding window problem is that you are given a linear data structure, such as a string or an array, and you must optimize for some constraint around a minimum or maximum number of things which must be true about a collection of items within the input string or input array. So, for example, some classic sliding window problems are “Longest Substring Without Repeating Characters,” “Longest Repeating Character Replacement,” “Minimum Window Substring,” and “Sliding Window Maximum.” The general idea for all sliding window problems is that you maintain a <em>window</em> while traversing across the linear data structure. The window is some sub-collection of elements inside the collection of elements contained in the array or string passed as a parameter.</p><p>We recognize the problem as a <em>sliding window</em> problem because 1, the question is literally called “Sliding Window Maximum,” and 2, there is some invariant to be maintained while keeping track of some piece of data the question asks us to return. Recognizing the question as a sliding window problem and <em>not</em> a graph, priority queue or linked list problem can only aid in fully understanding the question.</p><p><em>Methodological approach to solving sliding window problems</em></p><p>There are basic questions you want to answer in simple terms before implementing and writing your code. These questions are in play for <em>every </em>SWP.</p><ol><li>Does the question ask me to implement a <em>fixed-sized </em>sliding window or a <em>dynamically-sized</em> sliding window?</li><li>Under what condition does the right pointer move?</li><li>When will the function read the temporary solution?</li><li>How will the function decide on the optimal solution?</li><li>Under what condition does the left pointer move?</li><li>Which category does the SWP fall under?</li></ol><p>Next we can think about the form of the sliding window problem. Because sliding window problems always solve for some maximum or minimum subset of the input array or input string, <em>there are only</em> <em>so many</em> ways a sliding window problem can be presented.</p><ol><li><strong>Fast/slow</strong>: The right pointer moves faster than the left pointer. The question covered by this post on <a href="https://leetcode.com/problems/sliding-window-maximum/">LeetCode 239: “Maximum Window Substring”</a> is a fast/slow SWP.</li><li><strong>Fast/catchup</strong>: The only difference between the fast/slow problems and the fast/catchup problems is that fast/catchup problems have a left pointer which “jumps” to the location of the right pointer. <a href="https://leetcode.com/problems/maximum-subarray/">LeetCode 53. “Max Subarray”</a> is an example. The jump occurs conditionally upon some event happening such as the currentSumInteger in “Max Subarray” becoming negative.</li><li><strong>Fast/lagging</strong>: While looping over the array the function maintains an invariant where the solution can only be changed by an element which is a fixed number of spots away from the present array value. See the “<a href="https://leetcode.com/problems/house-robber/">House Robber</a>” problem.</li><li><strong>Front/back</strong>: The left pointer is initialized at the 0th index while the other pointer is initialized at the last index. See “<a href="https://leetcode.com/problems/trapping-rain-water/">Trapping Rain Water</a>.”</li></ol><p>Since every sliding window problem must fall into one of these four categories, we can ask “which category does the present SWP fall under?” We know the answer will always be one of these four choices: Fast/slow, fast/catchup, fast/lagging, and front/back.</p><p><em>The approach for “Sliding Window Maximum”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ByaNOEYOn15d2bu5" /></figure><ol><li>Does the question ask me to slide a <em>fixed-sized </em>window or a <em>dynamically-sized </em>window?</li></ol><ul><li><em>A fixed-sized window with a length of k.</em></li></ul><p>2. Under what condition does the right pointer move?</p><ul><li><em>The right pointer moves as long as the index of the right pointer is less than the length of the input array.</em></li></ul><p>3. When will the function read the temporary solution?</p><ul><li><em>The function reads the temporary solution after each time the right pointer’s index changes. The temporary solution in “Sliding Window Maximum” to keep track of is the maximum value which has been observed.</em></li></ul><p>4. How will the function decide on the optimal solution?</p><ul><li><em>As long as the right pointer index is less than the length of the input array, and as long as the size of the window equals k, then whatever the current maximum value which has been observed so far is pushed to the output array.</em></li></ul><p>5. Under what condition does the left pointer move?</p><ul><li><em>The left pointer moves when the window size has reached k.</em></li></ul><p>6. Which category does the present SWP fall under?</p><ul><li><em>“Sliding Window Maximum” is a fast/slow SWP.</em></li></ul><pre>const slidingWindowMaximum = (numsArr, kInt) =&gt; {<br>    if (kInt &gt; numsArr.length){<br>        return [];<br>    }<br>    let rightPtrInt = 0;<br>    let leftPtrInt = 0;<br>    let maxValInt = -Infinity;<br>    let maxValIndexInt = -1;<br>    let outputArr = [];<br>    while (rightPtrInt &lt; numsArr.length){<br>        let numInt = numsArr[rightPtrInt];<br>        if (numInt &gt;= maxValInt){<br>            maxValInt = numInt;<br>            maxValIndexInt = rightPtrInt;<br>        }<br>        rightPtrInt++;<br>        if (rightPtrInt - leftPtrInt === kInt){<br>            outputArr.push(maxValInt);<br>            // handle the case where the maxVal leaves when leftPtrInt is about to moves<br>            if (maxValIndexInt === leftPtrInt){<br>                maxValInt = -Infinity;<br>                // perform O(kInt) scan to find and store the maximum value in the window<br>                for (let xInt = leftPtrInt+1; xInt &lt; rightPtrInt; xInt++){<br>                    let numInt = numsArr[xInt];<br>                    if (numInt &gt;= maxValInt){<br>                        maxValInt = numInt;<br>                        maxValIndexInt = xInt;<br>                    }<br>                }<br>            }<br>            leftPtrInt++;<br>        }<br>    }<br>    return outputArr;<br>}<br><br>/* Tests */<br>let nums1Arr = [1,3,-1,-3,5,3,6,7];<br>let k1Int = 3;<br><br>let nums2Arr = [1];<br>let k2Int = 1;<br><br>let nums3Arr = [1, -1];<br>let k3Int = 1;<br><br>let nums4Arr = [1,3,1,2,0,5];<br>let k4Int = 3;<br><br><br>console.log(slidingWindowMaximum(nums1Arr, k1Int)); // Expect [3,3,5,5,6,7]<br>console.log(slidingWindowMaximum(nums2Arr, k2Int)); // Expect [1]<br>console.log(slidingWindowMaximum(nums3Arr, k3Int)); // Expect [1, -1] <br>console.log(slidingWindowMaximum(nums4Arr, k4Int)); // Expect [3,3,2,5] </pre><p><em>Time &amp; space complexities</em></p><p>The method I share here has a run-time of O(k*(N-k)). The window is size k. The function must scan the window N-k times in order to find the maximum value of the array.</p><p>“Wait,” you say, “I thought a sliding window problem can be implemented efficiently with a time complexity of O(N).” You would be right. There is a reason for implementing the O(k*(N-k)) first. This LeetCode problem is technically classified as a “hard” problem. While the solution presented here is not the most efficient solution, writing out this solution will help us to develop the intuition for solving <em>any</em> sliding window problem in the future. I chose to write about this problem because there is a very simple and straightforward notion of what a sliding window is. Like other sliding window problems, part of the problem consists of building the window, and part of the problem consists of doing something with the elements within the window, and then there is the straightforward notion of sliding the window over the input. Also, for what it’s worth, with the LeetCode tests as they are written the O(k*(N — k)) solution will pass. Do you have suggestions about how to implement a more efficient function in terms of time complexity? Leave your thoughts in the comment section below.</p><p>The space complexity of the function is O(N-k+1). The output array uses O(N) space, but since the window size is k in length, the space complexity is slightly less than N. The space complexity is actually just O(N-k+1). The number of elements in the output array is equal to how many times the window can be slid over the input array, or O(N-k) plus the maximum value of the window before the window begins to slide, which is O(1).</p><p><em>Edge case</em></p><p>The problem “Sliding Window Maximum” asks us to keep track of the maximum value inside a sliding window and cache the max value as the window slides over the input array. How big is the window sliding over the input array? The window’s size is fixed and not dynamic. Specifically, there are exactly <em>k</em> elements inside the window, where <em>k</em> is just an integer passed as a parameter. We also know if <em>k</em> is greater than the length of the input array, there is no possible solution. Sliding a window with a size k=5 elements over an array containing 3 elements is impossible.</p><pre>// Example 1<br>kInteger1 = 5;<br>array1 = [ 1, 2, 3];<br>// Diagram of the window before the window has moved: [ 1, 2, 3, _, _ ]<br>// Result: [], an empty array</pre><p>As we can see, when kInteger1 is greater than the length of array1 there is no valid window which can slide over the input array.</p><p><em>A note on the type of linear data structure in the input: array or string</em></p><p>I write functions in JavaScript, where you can convert strings into arrays using the .split() method. For example, you can convert str1 = “Chicago” into arr1 = [ “C”, “h”, “i”, “c”, “a”, “g”, “o”] by assignment with let arr1 = str1.split(“”). You can also convert an array into a string using the .join() method. Returning arr1.join(“”) returns “Chicago.” The point is this: don’t let the specific linear data structure worry you too much. If you <em>really</em> want to convert a string to an array because you prefer the methods associated with an array, that option is completely available for you. You actually might be really interested in using an array instead of a string since arrays have more methods available in JavaScript. Arrays also have methods which enable the array to be implemented as a queue, stack, or double-ended queue (deque).</p><p>You generally will be hard-pressed to find a moving window solution faster than O(N) time, also known as linear time, when analyzing the time complexity of a successful sliding window function. Since the optimal solution’s runtime is not more efficient than O(N), applying .split(“”) or .join(“”) is not going to adversely affect the overall runtime of your solution.</p><p><em>Softly typed JavaScript</em></p><p>If you have written in JavaScript as well as another language, such as C# or Java, you are surely aware a variable can be declared in JS without specifying the variable’s data type. There’s a lot to like about specifying what the data type of a particular variable will be. I have been writing JavaScript variables with this formula: <em>variableName + Int/Map/Set/Arr/Str/Node.</em> Specifying the variable type at the end of the variable’s name has proved clarifying and helpful when referencing a variable later. The variable’s name clearly tells you as a developer what data type to expect. No more re-checking your code to see whether a variable is an integer, a string, or something else. Let me know your thoughts on softly typed JavaScript in the comments.</p><p>That’s it for this post! I hope you have an amazing day and a wonderful journey as an engineer.</p><p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26a90285325b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Query Caching with Redis, Express, Node.js, and React]]></title>
            <link>https://medium.com/@gferowich/how-to-implement-query-caching-with-redis-express-node-js-and-react-3a4c4b530c6?source=rss-c09f73e554df------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a4c4b530c6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Grant Ferowich]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 21:58:51 GMT</pubDate>
            <atom:updated>2023-11-30T18:26:32.257Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><p>A quick guide for storing data from an API call in a cache.</p><p>In this post I cover the following:</p><p>1. Reasons you would want to implement a Redis cache</p><p>1a. Reduce the number of external API calls</p><p>1b. Speed up the process of data retrieval from your APIs</p><p>4. The O(1) look up property of the Redis cache.</p><p>5. Instantiating the Redis client in an Express file.</p><p>6. Performing read operations of the Redis cache.</p><p>7. Writing to the Redis cache.</p><p>8. Changing your Redis configuration file to ensure proper cache performance in a production environment.</p><p>Caching dramatically reduces latency of your web application. Specifically, this article will cover a strategy called query caching. Query caching is premised on a simple idea. You are retrieving some data from an API (application programmer interface) but you would like to do so less frequently. Query caching is great for storing data retrieved from an API which has a rate limit.</p><p>Another reason to store the data from an API call with a cache is to reduce the time it takes to get the data you want. Reading from a cache is 10 to 50 times faster than a network call to an API.</p><p>I am writing this post for people who are looking to implement a Redis cache and want a primer. The post could be read by beginner and intermediate programmers alike, or non-programmers. I will not assume you have any programming background. If you are new to Redis, here is where you can <a href="https://redis.io/docs/getting-started/installation/install-redis-on-mac-os/">install Redis on macOS</a>.</p><p>Back to the first reason. You want to reduce the number of API calls you are making by storing the results of an API request in a cache. Many APIs enforce a rate-limiting policy to restrict the number of times an IP (internet protocol) address may retrieve information from a specific resource.</p><p>There are good reasons for enforcing rate limiting. One reason someone — perhaps you, at some point — would want to implement a rate-limiter on an API you have developed is for security. Malicious traffic could potentially reach your API and degrade the performance of your API. A rate-limit policy can cut off certain types of malicious activity. For example, a certain IP address could send a very large amount of API requests to the API you built as part of a DDOS (distributed denial of service) attack. With rate-limiting in place, the malicious IP address would be prevented from making additional requests upon reaching the rate limit.</p><p>I will go ahead and simply share the Redis mechanism I implemented. I have an application which fetches data from the CoinGecko API. I don’t want to make a new request every time I want to read the data from the API. I only want to make one request per hour. If I made a new request every time I wanted to read the data, I could be cut off from the data within an hour by making too many requests. To jump over the API’s rate-limit policy I can implement a cache. Thanks to the cache I will store the data from the fetch which happens once per hour. This strategy is referred to as query caching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cng4bEsT53UgwEge4yL_iQ.png" /></figure><p>Another reason you might want to implement Redis is because your API request takes too long. Reducing the latency, that is, the time it takes for a page to load, below 200 milliseconds is definitely a solid goal to set out there for yourself. Feel free to make GET requests from your API on Postman to measure the time required to return data from an API. If you are implementing query caching, you are on the road to saving a lot of time.</p><p>A Redis cache, under the hood, is simply a hash map with keys and values. The same way you would use the .get(key) or .set(key, value) to append key-value pairs to a Map object in JavaScript, you similarly call set key value and get key from the Redis CLI (command line interface). The great part about the Redis cache is how this component leverages the amazing property of hash map lookups. The lookup time to access a value from a hash map data structure is O(1), or, constant time. You literally cannot retrieve data from a data store any faster than that.</p><p>A Redis cache will also live in memory, instead of on the disk, though Redis has gone ahead and added ways for users to enable disk persistence of a Redis cache. For the current implementation, I did not persist the Redis cache to the machine’s disk. Retrieving from memory, instead of disk, also supports fast lookup times.</p><p>The main requirement I worked with was this:</p><p>The server must refresh the data table once every 60 minutes (3600 seconds) with new data from the external API (CoinGecko). I used <a href="https://www.npmjs.com/package/node-cron">node-cron</a> to set up a function which will run once per hour to make sure the data in the cache is less than 60 minutes old at any given point in time.</p><p>Here is how part of the index.js file of the Express application looks.</p><pre>const axios = require(&#39;axios&#39;);<br>const cron = require(&#39;node-cron&#39;);<br>// ... other stuff<br>const coinGeckoAPIStr = &#39;https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&amp;order=market_cap_desc&amp;per_page=250&amp;page=1&amp;sparkline=false&amp;price_change_percentage=24h&#39;<br>const completeAPICall = async () =&gt; {<br>    const responseHM = await axios.get(coinGeckoAPIStr)<br>    try {<br>        const apiDataArr = (responseHM.data.sort((a, b) =&gt; a.market_cap_rank - b.market_cap_rank));<br>        await Coin.deleteMany();<br>        await Coin.insertMany(apiDataArr);<br>        console.log(&#39;API call was successfull.&#39;)<br>    } catch (errorHM) {<br>        console.error(&#39;API call failed: &#39;,errorHM )<br>    }<br>}<br><br>// schedule the api call to run every hour<br>cron.schedule(&#39;0 * * * *&#39;, () =&gt; {<br>    completeAPICall();<br>})</pre><p>The Redis cache is instantiated in the api/coins.js, where the API endpoints are defined.</p><pre>const express = require(&#39;express&#39;);<br>const router = express.Router();<br>const Redis = require(&#39;redis&#39;);<br>const Coin = require(&#39;../models/coin&#39;);<br><br>const redisClient = Redis.createClient({<br>  // the url field should be like this: redis://stuffstuffstuff<br>  url: ‘YOUR_REDIS_URL_HERE_’<br>})<br>const DEFAULT_EXPIRATION_INT = 3660;</pre><p>The Redis cache has a nice feature where you can set the cache to expire after a specified period. By letting the cache data expire you can ensure you will always be retrieving the most recent data. “But what happens when there is an error with how the data is retrieved from the Redis cache?” you may be asking. Great question. The logic for fetching data from the Redis cache works like this. The GET route checks if there is a value associated with the key unlocking the data. If the key is there — data is not null — then the Redis value associated with the key is passed back to the client making the request. This is how the cache is hit. If there is no value found when looking at the relevant key in the cache, then a call is made to the Mongo noSQL database (which is also developed around the idea of key-value pairs). The Mongo call is made with the Coin.find(), which returns an array.</p><pre>router.get(&#39;/get250&#39;, async (req, res) =&gt; {<br>    try {<br>      redisClient.get(&#39;250&#39;, async (error, data) =&gt; {<br>        if (error) {<br>          console.error(error)<br>        }<br>        if (data !== null){<br>          console.log(&#39;Cache hit&#39;)<br>          return res.json(JSON.parse(data))<br>        } else {<br>          console.log(&#39;Cache miss&#39;)<br>          const coins = await Coin.find()<br>          .sort({ createdAt: -1 })<br>          .limit(250);<br>          redisClient.setex(&quot;250&quot;, DEFAULT_EXPIRATION_INT, JSON.stringify(coins));<br>          res.json(coins);<br>        }<br>      })<br>    } catch (error) {<br>      console.error(&#39;Error retrieving coins:&#39;, error);<br>      res.status(500).send(&#39;An error occurred.&#39;);<br>    }<br>});</pre><p>Write operations to the cache are straightforward. Just as the read operation to the Redis cache is nested in the GET HTTP call, the write operation is nested in the POST HTTP call.</p><pre>router.post(&#39;/post&#39;, async (request, response) =&gt; {<br>    try {<br>        // isolate 250 coins from api call<br>        const coins = request.body;<br>        // post to the Time endpoint <br>        await Time.findOneAndUpdate({}, { lastUpdated: Date.now()}, { upsert: true});<br>        // post to the Coin endpoint<br>        await Coin.insertMany(coins)<br>        .then(() =&gt; {<br>            console.log(&#39;Coins were added to the database.&#39;);<br>            redisClient.setex(&quot;250&quot;, DEFAULT_EXPIRATION_INT, JSON.stringify(coins))<br>            response.status(200).send(&#39;Coins were added successfully.&#39;)<br>        }).catch(error =&gt; {<br>            console.error(&#39;Error adding coins to the database:&#39;, error)<br>            response.status(500).send(&#39;An error occurred.&#39;)<br>        })<br>    } catch (errorHM) {<br>        console.log(&#39;Request Body&#39;, request.body);<br>        response.status(400).json(console.log(&#39;Error!&#39;, errorHM));<br>    }  <br>})</pre><p>Note that when you post data to the Redis cache, you will want to use JSON.stringify(). When you retrieve data from the Redis cache, you will want to use JSON.parse(). Thanks to this architecture the React calls are the same before implementing the cache as they are after implementing the cache.</p><p>Story time. When I first set up the cache, I was able to test out the “cache hit” and “cache miss” functionality without any problem. Next, I committed and pushed the code to Github. Lo-and-behold, instead of seeing “cache hit” and “cache miss” messages I was seeing:</p><pre>{&quot;errorType&quot;:&quot;Error&quot;,<br>&quot;errorMessage&quot;:&quot;Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379&quot;,&quot;code&quot;:&quot;ECONNREFUSED”}</pre><p>This all occurred on a MacBook Pro with an AppleM1 Max chip.</p><p>When making requests to localhost:3000/api/coin/get250, I was seeing the “cache hit” messages without a problem. When making requests to the production URL, I ended up seeing the failed connection message. Here are the steps which ended up producing the desired behavior:</p><ol><li>Open the redis configuration file. In the Unix terminal:</li></ol><pre>code /usr/local/etc/redis.conf</pre><p>2. Change the bind: Control-F “bind”. Then Uncomment this line: bind * -::*</p><p>3. Change the port. When you set up the production version of Redis, which you can do by setting up an account with Redis and then logging in, there will be an endpoint. At the end of the endpoint there is a port number. The port number you see after setting up your endpoint is the port number you want to append to the Redis configuration file. This is what worked for me. YMMV (your mileage may vary.)</p><p>4. Finally, make sure the URL you drop into the Redis client looks something like this: redis://&lt;username&gt;:&lt;password&gt;@YOUR_DATABASE_ALIAS_HERE.</p><p>You can retrieve your database alias from RedisInsight, or whatever.</p><p>These four steps were enough to resolve the failed connection error message.</p><p>That is the post! Thank you for reading. I hope you have an amazing experience in the rest of your development journey.</p><p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a4c4b530c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to change the default color in Material UI?!]]></title>
            <link>https://medium.com/@gferowich/how-to-change-the-default-color-in-material-ui-8d4704b81502?source=rss-c09f73e554df------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d4704b81502</guid>
            <dc:creator><![CDATA[Grant Ferowich]]></dc:creator>
            <pubDate>Sat, 07 Mar 2020 16:09:42 GMT</pubDate>
            <atom:updated>2023-11-30T18:27:44.907Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><p>The first time using Material UI, my project partner and I did not have time to dig into customizing the theme. The second time I used Material UI, I carved out time to customize the theme.</p><p>As a quick background, Material UI is a React UI framework. I’ve really enjoyed using it in my last two projects because it helps turbocharge the feel of your UI to be much more modern.</p><p>If you are getting started, <a href="https://material-ui.com/getting-started/templates/">this page</a> featuring Material UI templates definitely is not the worst place to start to figure out how to get rolling with this framework.</p><p>Okay, back to the fun stuff. Material UI has blue and dark pink built in as the primary and secondary colors for the theme. Suppose you <em>only want to customize the color</em> for now. Suppose you bootstrapped your project with</p><pre>create-react-app</pre><p><strong>FIRST: </strong>Import createMuiTheme and Theme provider from material-ui/core in the index.js file</p><pre>import { createMuiTheme, ThemeProvider } from &quot;@material-ui/core&quot;;</pre><p><strong>NEXT</strong>: Overwrite the custom palette in index.js</p><pre><strong>const</strong> theme = createMuiTheme({</pre><pre>   palette: {</pre><pre>      primary: {</pre><pre>         main: &quot;#ff8f00&quot; // This is an orange looking color</pre><pre>                },</pre><pre>      secondary: {</pre><pre>         main: &quot;#ffcc80&quot; //Another orange-ish color</pre><pre>                 }</pre><pre>            },</pre><pre>fontFamily: font // as an aside, highly recommend importing roboto font for Material UI projects! Looks really nice</pre><pre>});</pre><p>Where do you get the hex codes, you ask? Check out the Material UI documentation on colors <a href="https://material-ui.com/customization/color/">here</a>. You can also do a lot more with colors than I did, but now this lean implementation is available for you as well.</p><p><strong>FINALLY</strong>: Wrap your app with the ThemeProvider in the index.js file. N.B. Use &lt;ThemeProvider&gt;&lt;/ThemeProvider&gt;. Do<em> not</em> use &lt;MuiThemeProvider&gt;&lt;/MuiThemeProvider&gt;. Learn from my mistakes, please, I insist. Using MuiThemeProvider won’t change the color of the app, but ThemeProvider will.</p><pre>ReactDOM.render(&lt;ThemeProvider theme={theme}&gt;&lt;App /&gt;&lt;/ThemeProvider&gt;,document.getElementById(&quot;root&quot;));</pre><p>That’s all there is to it! Here’s the final look!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bYja2w4FwAxmyOSVd_TNQ.png" /></figure><p>I used this implementation for CoinTiger, which is available for you to check out <a href="http://cointiger.herokuapp.com/">here</a>.</p><p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d4704b81502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use CoinGecko’s Free API to Get Digital Asset Data: Just the Basics]]></title>
            <link>https://medium.com/coinmonks/how-to-use-coingeckos-free-api-to-get-digital-asset-data-just-the-basics-d46f232926cb?source=rss-c09f73e554df------2</link>
            <guid isPermaLink="false">https://medium.com/p/d46f232926cb</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Grant Ferowich]]></dc:creator>
            <pubDate>Tue, 25 Feb 2020 00:55:01 GMT</pubDate>
            <atom:updated>2024-04-09T18:39:53.384Z</atom:updated>
            <content:encoded><![CDATA[<h3>Crypto Data API for Javascript Developers: A Beginner’s Guide</h3><p><strong>Get 20% off any CoinGecko API plan when you subscribe with my referral code “GRANT20” at </strong><a href="http://www.coingecko.com/api"><strong>www.coingecko.com/api</strong></a><strong>.</strong></p><p>Software developers talk about APIs a lot. What is an API? API stands for an application programming interface. I wanted to gather specific market data on Bitcoin, Ethereum and other digital assets for a JavaScript project I was working on. My first stop was CoinGecko.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*M4pePOxyzZ5BfowWxLlsfg.png" /><figcaption>CoinGecko is free to use and allows up to 100 requests per minute.</figcaption></figure><p>I chose CoinGecko’s API because the other major digital asset information site, CoinMarketCap, is notorious for publishing <a href="https://www.coindesk.com/for-15k-hell-fake-your-exchange-volume-youll-get-on-coinmarketcap">fake volume data on coins</a>.</p><ol><li>Decide what data you want to get. My application required current market price for a given coin, and the market price of a coin on a certain historical date, and a snapshot of the current market.</li></ol><p><strong>a.</strong> Go to <a href="https://www.coingecko.com/en/api">https://www.coingecko.com/en/api</a> and scroll about halfway down. There, you’ll see the types of requests you can make. Since my application needs to bring in some data from CoinGecko, I want to make a GET request. That’s exactly what CoinGecko enables. Wicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjhKET3k4zOgvpoWzv0HcQ.png" /></figure><p><strong>b.</strong> I will use <strong>/simple/price </strong>to get current market prices of coins X, Y, and Z<strong>.</strong> I will use<strong> /coins/{id}/history </strong>to get the price of a coin at some previous date.</p><p>2. Test how the data will be sent to your application. The testing environment on CoinGecko was excellent. It gives you an example of exactly how the information will pass to my application when I make a request. Let’s say I want to get the current market prices of <a href="https://blog.coincodecap.com/tag/bitcoin/">Bitcoin</a> and Ether. I can input these parameters right in the browser. Be sure to separate the ids of coins only with a comma, and no spaces, or you will hit a problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kd7o3obQ4QuBdANNo5y_Hw.png" /></figure><p>Click <strong>execute.</strong></p><p>CoinGecko spits out the response it will send when your application makes this same request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9BCbp7WIxMSl32wy9NLWg.png" /></figure><p>Great, so now we know that <a href="https://blog.coincodecap.com/tag/bitcoin/">bitcoin</a>.usd will bring out 9627.02 as a number from this object. Check it out by going to the API, copying that data structure, pasting it in your console, and testing out how to get the information you need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*jv1DatT_wLJkR7n_ruOLbw.png" /></figure><p>3. Import the dependencies in JavaScript</p><p>All you need is to run from the terminal:</p><pre>npm install &#39;coingecko-api&#39;</pre><p>You may want to double check this lands in your package.json file like so:</p><pre>&quot;coingecko-api&quot;: &quot;^1.0.10&quot;</pre><p>Nice and easy!</p><p>You only need the dependency to use the node.js wrapper, or else you can just hit the URL directly. (See the implementation below.)</p><p>4. Make your requests.</p><p>Lesson learned #1: If you need to get data for multiple coins, put them in an array when sending your fetch request to get the data.</p><p>Lesson learned #2: If the fetch request throws an error on historical queries, it may be because the data is only served from since the time CoinGecko started tracking that coin.</p><p>Lesson learned #3: Don’t forget that await functions (like this API query) must be conducted inside an async function. Here’s an implementation using the node.js wrapper inside a React class component:</p><pre><strong>async</strong> componentDidMount() {</pre><pre>await this.CoinGeckoClient.coins.markets(<br>{ vs_currency: &quot;usd&quot;,<br>  order: &quot;market_cap_desc&quot;,<br>  per_page: 100,<br>  page: 1,<br>  sparkline: false,<br>  price_change_percentage: &quot;24h&quot;})<br>.then(data <strong>=&gt;</strong> console.log(data))}</pre><p>Lesson learned #4: Running your requests in a JS file that is separate from your application can help avoid headaches. Just use that environment to practice how you’ll consume the data, and where you’ll send it. I spent half-a-day practicing requests in a coin-gecko-api.js file and rendering them in a simple react app just to get a feel for making the different requests. Time well-spent.</p><p>Here’s how an implementation of a historical request might look:</p><pre><strong>const </strong>getHistoricalPrice<strong> = async </strong>event =&gt; {</pre><pre><strong>let </strong>currency1API= &quot;bitcoin&quot;;<br><strong>let </strong>indexDate=&quot;01-01-2020&quot;;<strong><br>let</strong> string = &quot;https://api.coingecko.com/api/v3/coins/&quot; + currency1API +&quot;/history?date=&quot;+indexDate+&quot;&amp;localization=false&quot;;</pre><pre>await fetch(string)<br>.then(resp <strong>=&gt;</strong> resp.json())<br>.then(data <strong>=&gt;</strong> console.log(data.market_data.current_price.usd))}</pre><pre>//=&gt; 7195.15 </pre><p>5. Do what you want with the data!</p><p>Now you’ve got the data all ready to go. Who dares wins!</p><blockquote><a href="https://curiousweekly.com/"><strong>Curious Weekly — writing inspired by curiosity</strong></a>.</blockquote><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h4>Also, Read</h4><ul><li><a href="https://medium.com/coinmonks/how-to-use-coingeckos-free-api-to-calculate-roi-of-a-short-position-2db5f6f5b294">How to Use CoinGecko’s Free API to Calculate the ROI of a Short Position</a></li><li><a href="https://medium.com/coinmonks/generating-the-roi-of-a-long-position-with-coingeckos-api-step-by-step-8733e90918be">How to Use CoinGecko’s Free API to Calculate the ROI of a Long Position: Step-by-step</a></li><li><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">Copy Trading</a> | <a href="https://medium.com/coinmonks/crypto-tax-software-ed4b4810e338">Crypto Tax Software</a></li><li><a href="https://coincodecap.com/grid-trading">Grid Trading</a> | <a href="https://medium.com/coinmonks/the-best-cryptocurrency-hardware-wallets-of-2020-e28b1c124069">Crypto Hardware Wallet</a></li><li><a href="http://Top 4 Telegram Channels for Crypto Traders">Crypto Telegram Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bot</a></li><li><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Best Crypto Exchange in India</a></li><li><a href="https://medium.com/coinmonks/best-crypto-apis-for-developers-5efe3a597a9f">Best Crypto APIs</a> for Developers</li><li>Best <a href="https://medium.com/coinmonks/top-5-crypto-lending-platforms-in-2020-that-you-need-to-know-a1b675cec3fa">Crypto Lending Platform</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li><li><a href="https://coincodecap.com/ascendex-staking">AscendEx Staking</a> |<a href="https://coincodecap.com/bot-ocean-review"> Bot Ocean Review</a> |<a href="https://coincodecap.com/bitcoin-wallets-india"> Best Bitcoin Wallets</a></li><li><a href="https://coincodecap.com/bitget-review">Bitget Review</a> |<a href="https://coincodecap.com/gemini-vs-blockfi"> Gemini vs BlockFi</a> |<a href="https://coincodecap.com/okex-futures-trading"> OKEx Futures Trading</a></li><li><a href="https://coincodecap.com/crypto-trading-bots-in-the-us">Best Crypto Trading Bots in the US</a> |<a href="https://coincodecap.com/changelly-review"> Changelly Review</a></li><li><a href="https://coincodecap.com/crypto-arbitrage-in-india">Earn Passive Income Using Crypto Arbitrage In India</a></li><li><a href="https://coincodecap.com/huobi-review">Huobi Review</a> |<a href="https://coincodecap.com/okex-margin-trading"> OKEx Margin Trading</a> |<a href="https://coincodecap.com/futures-trading"> Futures Trading</a></li><li><a href="https://coincodecap.com/sparrow-exchange-review">Sparrow Exchange Review</a> |<a href="https://coincodecap.com/nash-exchange-review"> Nash Exchange Review</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d46f232926cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/how-to-use-coingeckos-free-api-to-get-digital-asset-data-just-the-basics-d46f232926cb">How to Use CoinGecko’s Free API to Get Digital Asset Data: Just the Basics</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Model-View-Controller(MVC) architecture versus front-end web programming. What are the differences?]]></title>
            <link>https://medium.com/@gferowich/model-view-controller-mvc-architecture-versus-front-end-web-programming-what-are-the-differences-5b17de85d922?source=rss-c09f73e554df------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b17de85d922</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Grant Ferowich]]></dc:creator>
            <pubDate>Fri, 03 Jan 2020 19:44:14 GMT</pubDate>
            <atom:updated>2023-11-30T18:28:03.681Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><p>Model-View-Controller (MVC) architecture with Ruby on Rails versus a single page application with vanilla JavaScript. What are the differences?</p><p>The primary difference between the MVC architecture and the single page application (SPA) is how the browser loads the content of an HTML file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*zELSGyg-SOab5GwXIw6ttA.png" /><figcaption>Screenshot</figcaption></figure><p>In 311Now, which uses Ruby exclusively, my partner and I had multiple <strong>index.html.erb</strong> and <strong>show.html.erb</strong> and <strong>new.html.erb</strong> pages that the browser had to read to get content displayed on the browser.</p><h3>An SPA has … one HTML file</h3><p>IOU A Vowel has one <strong>index.html</strong> file, and the whole application runs from that file. IOU A Vowel is a simple application that has two pages seen by users: the login screen and the quiz page. Instead of pointing to different HTML files to navigate around an application, JavaScript has some powerful abilities to dynamically display what gets seen by users on the browser.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FYr5XipSHdyfK4kUUiK%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FYr5XipSHdyfK4kUUiK&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FYr5XipSHdyfK4kUUiK%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="355" frameborder="0" scrolling="no"><a href="https://medium.com/media/3356aa37b38995549a5caaf1be4e246f/href">https://medium.com/media/3356aa37b38995549a5caaf1be4e246f/href</a></iframe><p>For IOU A Vowel, the meat of the difference between and MVC approach and SPA was the V of MVC, the view.</p><p>JavaScript empowers you as a developer to dynamically display content on the screen by manipulating the Document Object Model, or “DOM.” The browser (Google Chrome, Mozilla Firefox, etc.) renders stuff based on what’s happening with the DOM.</p><p>The DOM brings together the HTML, CSS, and JavaScript code into one package that your browser shows to users. With JavaScript the page becomes interactive based on how the user interacts with the page. This post will cover a couple clear, isolated examples of what is meant by that.</p><p>The <a href="https://www.w3.org/TR/DOM-Level-3-Core/introduction.html">technical definition</a> of the DOM is:</p><p>“an application programming interface (<a href="https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-API">API</a>) for valid <a href="https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-HTML">HTML</a> and well-formed <a href="https://www.w3.org/TR/DOM-Level-3-Core/glossary.html#dt-XML">XML</a> documents. It defines the logical structure of documents and the way a document is accessed and manipulated.”</p><h3>Changing what parts of the HTML file render in the browser</h3><p>For example, clicking on the <strong>Click here</strong> button in IOU A Vowel tells the JavaScript file to execute some logic that tells the DOM to show the quiz page and hide the welcome page.</p><pre>const gameButton = document.getElementById(&quot;game&quot;)</pre><pre>gameButton.addEventListener(&quot;click&quot;, firstMove)</pre><pre>function firstMove() {</pre><pre>   let x = document.getElementById(&quot;div1&quot;)</pre><pre>   let y = document.getElementById(&quot;div2&quot;)</pre><pre>      if (x) {</pre><pre>         if (x.style.display == &quot;none&quot;) {</pre><pre>         x.style.display = &quot;block&quot;;</pre><pre>         y.style.display = &quot;none&quot;<br>      } else {</pre><pre>         x.style.display = &quot;none&quot;;</pre><pre>         y.style.display =&quot;block&quot;} <br>}</pre><p>To break this code down, first consider this is in the <strong>index.js</strong> file. The gameButton variable corresponds to the <strong>click here</strong> button on the page. An event listener makes sure the button knows that if a <em>click </em>event happens, then the function named <em>firstMove</em> will run.</p><p>The whole application occurs in the <strong>div1 </strong>and <strong>div2 </strong>elements. The second part of the ‘else’ statement is what toggles the view from the welcome page to the actual quiz after the button is clicked.</p><p>In Rails, there would have to be a route specifying how a user can navigate through the application. With a SPA, you don’t really focus on specifying routes as much as building out an intuitive user flow and then coding that into the JavaScript file. An <a href="https://uxdesign.cc/when-to-use-user-flows-guide-8b26ca9aa36a">operative definition</a> for userflow is “a series of steps a user takes to achieve a meaningful goal.”</p><h3><strong>Using JS to send data to the Server/API</strong></h3><p>Separately, the <strong>submit</strong> button sends some data to a Rails API, which persists the name entered in the text field to a SQL database. IOU Vowel uses Ruby on Rails to build an API. The API is essentially an object that stores data to be used inside the application.</p><p>Note that some APIs are useful for the public. If I wanted to gather Bitcoin price data, I might make requests to an exchange API that’s also available for a person in an office down the street.</p><p>With front-end programming in JavaScript, it can be helpful to visualize where events are going on inside the application. The screen’s button listens for a certain kind of event and recognizes it. Similar to how the controller functions in Rails, the .js file handles the input data, i.e the user’s name, and then does something with the piece of name data.</p><p>You can also notice that the DOM is manipulated when a user enters a name: a welcome message appears on the page saying, “Hi, <em>username</em>!” Adding the new <em>element </em>viewable on the page is an example of manipulating the DOM. This is a small example, but the concept of updating the page based on how a user interacts with it is at the heart of engagement activities on Twitter, for instance, when you like or retweet a tweet.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FPjUnCMVr88XONiJLER%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FPjUnCMVr88XONiJLER&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FPjUnCMVr88XONiJLER%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="355" frameborder="0" scrolling="no"><a href="https://medium.com/media/91855ebf4e6ca190a6bbe41346db6b91/href">https://medium.com/media/91855ebf4e6ca190a6bbe41346db6b91/href</a></iframe><p>There’s a method in the .js file that communicates with the API by posting new data to it. This is at the core of what front-end development is about recognizing events, manipulating the DOM, and communicating with the server.</p><p>You can view the repository for the project on GitHub <a href="https://github.com/Clariti23/IOU-a-vowel-1">here</a>. As always, feedback is welcome!</p><p><a href="https://curiousweekly.com/"><strong><em>Curious Weekly — writing inspired by curiosity</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b17de85d922" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>