<?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 Arion Sprague on Medium]]></title>
        <description><![CDATA[Stories by Arion Sprague on Medium]]></description>
        <link>https://medium.com/@arionsprague?source=rss-56f11048563e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z4AMeqGTwS1CAwNWWuR6DQ.jpeg</url>
            <title>Stories by Arion Sprague on Medium</title>
            <link>https://medium.com/@arionsprague?source=rss-56f11048563e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 19:08:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arionsprague/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[Binary, Hex, and 60 Minutes Per Hour]]></title>
            <link>https://medium.com/@arionsprague/binary-hex-and-60-minutes-per-hour-77ec54709d97?source=rss-56f11048563e------2</link>
            <guid isPermaLink="false">https://medium.com/p/77ec54709d97</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[binary]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[numbers]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Arion Sprague]]></dc:creator>
            <pubDate>Wed, 19 Jun 2019 00:49:17 GMT</pubDate>
            <atom:updated>2019-06-19T00:49:17.884Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the first math tricks we learn as kids is to count to 10. Why not 13, or 24? Because 10 feels like a whole, round number. The reason is because we use a base-10 numerical system.</p><h3>The number five vs. the letter 5</h3><p>If I say “grab five sandwiches from the store”, you immediately know what I mean. If I text you “grab 5 sandwiches”, you understand that means the same thing. However, the first sentence used the word “five”, and the second used a letter that I know means “five”. 5 is a letter that represents the <em>idea</em> of five.</p><p>It’s a weird idea, but you’ve probably already learned it without knowing. What’s the Roman numeral V? It’s five. Both 5 and V are letters for “five”.</p><h3>Different numerical bases</h3><p>A base-10 system is a system where up to ten numbers can be represented with a single character:</p><pre>0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10</pre><p>0–9 are good. Once we reach ten, we need to use two letters: 1 and 0. What if we only had six characters?</p><pre>0<br>1<br>2<br>3<br>4<br>5<br>10</pre><p>In a base-6 system, I need to use two characters to represent six. It looks like ten, but in base-6 the characters 10 equal six. If I wanted to represent ten, it would be 14.</p><h3>Binary</h3><p>Binary is a base-2 system. We use it in computers because it’s easy to represent two digits with an electrical charge.</p><pre>0<br>1<br>10 = two<br>11 = three<br>100 = four<br>101 = five</pre><h3>Hex</h3><p>We can also have more than ten characters. Hex is a base-16 system that’s often used to represent color. It’s all over CSS. If we want a base &gt; ten, we need more characters. Hex uses letters.</p><pre>0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>A = ten<br>B = eleven<br>C = twelve<br>D = thirteen<br>E = fourteen<br>F = fifteen</pre><p>Two divides evenly into sixteen, which makes it really useful for representing binary. Each letters is four bits, which makes two hex letters a byte.</p><pre>(base-10) = 255<br>(base-2)  = 1111 1111<br>(base-16) = FF</pre><p>For RGB colors on the web, a six letter hex number represents your three color values. The first two are red, the next two are green, and the last two are blue.</p><pre>.css-class {<br>  color: #FFFFFF<br>}</pre><h3>Ancient Babylon and the clock</h3><p>We inherited our modern clock from Babylon. Like, the biblical one. Babylon had a base-60 system, which means representing sixty characters was really intuitive. They liked sixty because it’s dividisible by a lot of things (six in total).</p><p>Since they were the first to codify time into it’s discrete units, they used the most natural and intuitive number of the time: sixty. If we built modern time time today, we might have 100 seconds to the minute instead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77ec54709d97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Typescript Generic Function Splat]]></title>
            <link>https://medium.com/@arionsprague/typescript-generic-function-splat-f632a89b924c?source=rss-56f11048563e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f632a89b924c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Arion Sprague]]></dc:creator>
            <pubDate>Sat, 15 Jun 2019 18:21:25 GMT</pubDate>
            <atom:updated>2019-06-15T18:21:25.399Z</atom:updated>
            <content:encoded><![CDATA[<p>Good lord, that title is dense. We’ll eventually use type inference to do all sorts of cool things with method signatures, but let’s start with the last two words: function splat. If you’re using ES6, you have access to the fantastic splat operator. It’s an easy way of letting a function have an arbitrary number of arguments:</p><pre>function sum(...args) { // &lt;= Splat!<br>  return args.reduce((x, y) =&gt; x + y, 0);<br>}<br>sum(1, 5, 9) === 15</pre><p>Splats offer an easy tool to make wrapper functions. For example, let’s say I wanted a generic memoize function:</p><pre>function cacheKey(...args) { // good enough for demo<br>  return args.map(String).join(&#39;.&#39;);<br>}</pre><pre>function memoize(fn) {<br>  const cache = {}; // Saves the values<br>  return (...args) =&gt; {<br>    const key = cacheKey(...args);<br>    if (!cache[key]) { // Not in the cache? Call fn.<br>      cache[key] = fn(...args); // Now it&#39;s in the cache.<br>    }<br>    return cache[key];<br>  }<br>}</pre><p>Now I can easily wrap expensive functions in a cache.</p><pre>const cachedFetch = memoize(fetch);<br>cachedFetch(&quot;/api/endpoint&quot;);</pre><p>Subsequent calls to cachedFetch(“/api/endpoint”) will pull the value right from the cache.</p><p><strong>NOTE: </strong>You probably don’t <em>really</em> want to use memoize for caching API calls. You miss out on cache invalidation, and other nice things. However, you can tweak the memoize code to work with a lot of other caching solutions (E.g. React’s upcoming createResource).</p><h3>Typescript</h3><p>That’s grand. Now let’s add Typescript. We’ll start with simple examples, then work our way to a generic memoize function which keeps track of fns argument types.</p><pre>function sum(...args: number[]) { // args only allows numbers<br>  return args.reduce((x, y) =&gt; x + y, 0);<br>}<br>sum(1, 5, 9) === 15</pre><p>For sum, it’s really easy. args can only be of type number[]. We’re not taking a callback function, and we’re not returning a new function.</p><h3>Generics</h3><p>memoize is a lot more complicated. We’ll get to it in a moment, but we need to cover generics and tuples first. Generics are great. Similar to how we pass arguments into a function, we can pass types in too.</p><pre>function identity&lt;T&gt;(x: T): T {<br>  return x;<br>}<br>const val = identity(&quot;hello&quot;);</pre><p>Since I’m passing in a string for x, Typescript infers that T is a string. Therefore the return value is string, and val is also a string.</p><p>Generics also let us limit the the types that can be passed in.</p><pre>type Addable = string | number;<br>function add&lt;T extends Addable&gt;(x: T, y: T): T {<br>  return x + y;<br>}</pre><pre>add(4, 5) === 9;<br>add(&quot;hello &quot;, &quot;world&quot;) === &quot;hello world&quot;;<br>add(true, &quot;hello&quot;) // Won&#39;t accept boolean<br>add(4, &quot;hello&quot;) // And T must be consistent.</pre><p>Again, Typescript infers what T is. And it’s <em>really</em> good at inferring. Let’s extend add to allow an arbitrary number of arguments. It’s generic splat time.</p><pre>type Addable = string | number;<br>function add&lt;T extends Addable&gt;(...args: T[]): T {<br>  return args.reduce((x, y) =&gt; x + y, 0);<br>}</pre><pre>add(4, 5, 6) === 9;<br>add(&quot;hello&quot;, &quot; &quot;, &quot;world&quot;) === &quot;hello world&quot;;</pre><p>This looks identical to our sum function, but it accepts more types. Typescript infers the types correctly. Using this function is as easy as JS, but still provides type safety.</p><h3>Tuple types</h3><p>Before we tackle memoize, we need to understand how tuples work in Typescript. A tuple is like a list, but it has a fixed length and fixed types.</p><pre>// Array<br>const array: Array&lt;string | number&gt; = [&quot;hello&quot;, 5];<br>const first = array[0]; // type is string | number, value = &quot;hello&quot;<br>const second = array[1]; // type is string | number, value = 5<br>const third = array[2]; // type is string | number, value = undefined :(</pre><pre>// Tuple<br>const tuple: [string, number] = [&quot;hello&quot;, 5];<br>const one = tuple[0]; // type is string, value = &quot;hello&quot;<br>const two = tuple[1]; // type is number, value = 5<br>const three = tuple[2]; // Won&#39;t compile :)</pre><p>An array value can be <em>either</em> an array type <em>or </em>a tuple type. If you’ve used React’s useState, you’ve already used tuples.</p><pre>function MyComponent() {<br>  const [count, setCount] = useState(0);<br>  ... // more code here.<br>}</pre><p>Typescript knows that val is a string and setCount is a (val: string) =&gt; void because useState returns a tuple.</p><p>We can rewrite our add function from earlier using tuples.</p><pre>type Addable = string | number;<br>function add&lt;T extends Addable&gt;(...args: [T, T]) {<br>  return args[0] + args[1];<br>}<br>add(1); // Typescript error: Not enough args<br>add(1, 2) === 3;<br>add(1, 2, 3); // Typescript error: too many args</pre><p>I would never write a function like this directly, but tuples + splats is extremely powerful when used with type inference.</p><h3>Type inferred memoize</h3><p>Here’s the whole, working memoize function. It will take any function, infer the arguments (as a tuple) and the return type. It returns a new function with the exact same type signature. The key to all of this is in the Fn type defined below:</p><pre>interface Cache {<br>  [key: string]: any;<br>}</pre><pre>type Fn&lt;<br>  TArgs extends unknown[], // This is the magic<br>  TResult<br>&gt; = (...args: TArgs) =&gt; TResult; // along with this.</pre><pre>function cacheKey(...args: any[]) {<br>  return args.map(String).join(&#39;.&#39;);<br>}</pre><pre>function memoize&lt;<br>  TArgs extends unknown[],<br>  TResult<br>&gt;(fn: Fn&lt;TArgs, TResult&gt;): Fn&lt;TArgs, TResult&gt; {<br>  const cache: Cache = {}; <br>  return (...args: TArgs) =&gt; {<br>    const key = cacheKey(...args);<br>    if (!cache[key]) {<br>      cache[key] = fn(...args);<br>    }<br>    return cache[key];<br>  }<br>}</pre><pre>const cachedFetch = memoize(fetch);<br>cachedFetch(&quot;/api/endpoint&quot;); // It knows this is a promise</pre><p>TArgs extends unknown[] will infer the most specific type it can. In this case, that’s fns arguments as a tuple. Since our return type is the same, our cachedFetch function just works.</p><h3>Using TArgs elsewhere</h3><p>Looking at the cacheKey function, I can think of plenty of cases where that breaks. memoize can’t know all of the use cases, so let’s take cacheKey as an argument. It should take the same arguments as fn, which we fortunately have.</p><pre>interface Cache {<br>  [key: string]: any;<br>}</pre><pre>type Fn&lt;<br>  TArgs extends unknown[],<br>  TResult<br>&gt; = (...args: TArgs) =&gt; TResult;</pre><pre>// New type<br>type CacheKeyFn&lt;TArgs extends unknown[]&gt; = (...args: TArgs) =&gt; string</pre><pre>function memoize&lt;<br>  TArgs extends unknown[],<br>  TResult<br>&gt;(<br>  fn: Fn&lt;TArgs, TResult&gt;,<br>  cacheKey: CacheKeyFn&lt;TArgs&gt; // Same TArgs<br>): Fn&lt;TArgs, TResult&gt; {<br>  const cache: Cache = {}; <br>  return (...args: TArgs) =&gt; {<br>    const key = cacheKey(...args);<br>    if (!cache[key]) {<br>      cache[key] = fn(...args);<br>    }<br>    return cache[key];<br>  }<br>}</pre><p>Typescript will infer TArgs from fn, then enforce that cacheKey has the same signature. That’s great.</p><p>Typescript’s generics allow us to write type-safe code that (mostly) feels like Javascript. The type definitions can be challenging at first, but inference is powerful enough to make <em>using</em> these functions feel almost like writing vanilla JS. And not having a user discover a cache collision (or other nasty bug) makes the extra overhead worth it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f632a89b924c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Closures, Hopefully Simple]]></title>
            <link>https://medium.com/@arionsprague/javascript-closures-hopefully-simple-ce9aed70f220?source=rss-56f11048563e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9aed70f220</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Arion Sprague]]></dc:creator>
            <pubDate>Fri, 14 Jun 2019 21:24:17 GMT</pubDate>
            <atom:updated>2019-06-14T22:10:05.931Z</atom:updated>
            <content:encoded><![CDATA[<p>Closures are one of the most confusing parts of Javascript. They’re surprisingly simple once you get them, but getting to the ‘aha’ moment is tough. I’m going to break down the concepts you need to understand closures</p><p><strong>WARNING: </strong>I’m going to use some contrived, stupid examples. This all culminates in real-world, extremely useful stuff. But the intermediate steps just look pointless. Bear with me.</p><h3>Functions as values</h3><p>In Javascript, functions can be passed around like numbers, strings, or any other value. If you’ve ever written an express app, or used a React event handler or hook, you’ve already done this. From the <a href="https://expressjs.com/en/starter/hello-world.html">Express Hello World example</a>:</p><pre>app.get(‘/’, (req, res) =&gt; res.send(‘Hello World!’));</pre><p>The first argument is a string, the second argument is a function. Express can call this function whenever it wants to run our code. I can rewrite the example to make it more obvious</p><pre>function hello(req, res) {<br>    return res.send(‘Hello World!’);<br>}</pre><pre>app.get(‘/’, hello);</pre><p>Let’s write our own code that passes around a function. In this case, I’m going to return a function instead of taking one in as an argument. Full disclosure: it’s a stupid function.</p><pre>function createMessage() {<br>  return () =&gt; {<br>    return &quot;hello&quot;;<br>  }<br>}<br>const message = createMessage(); // Create a new function<br>message() === &quot;hello&quot;; // Sweet.</pre><h3>The function is created when?</h3><p>So, what’s happening here? When I call createMessage, it creates a brand new function and returns it. I store that in const message, then call it on the next line. <strong>Super important: </strong>every time I call createMessage, it returns a <em>different</em> function. Check this out:</p><pre>function createMessage() {<br>  return () =&gt; {<br>    return &quot;hello&quot;;<br>  }<br>}<br>const message1 = createMessage();<br>const message2 = createMessage();</pre><pre>createMessage === createMessage; // Yep.<br>message1 !== message2; // THIS IS IMPORTANT! NOT EQUAL<br>message1() === message2(); // They return the same value, though</pre><p>Again, every time I call creatMessage, a <em>new</em> function is created, then returned. This isn’t a closure, but it’s <em>really</em> close.</p><h3>A Closure</h3><p>I can turn createMessage into a closure really, really easily.</p><pre>function createMessage() {<br>  const message = &quot;hello&quot;;<br>  return () =&gt; {<br>    return message;<br>  }<br>}<br>const message = createMessage();<br>message() === &quot;hello&quot;; // Still the same</pre><p><em>A closure is a function (child) inside of another function (parent), that references a variable in the parent’s scope.</em></p><p>If it feels underwhelming, that’s fine. The code looks like it should just work.</p><p>If it feels overwhelming, that’s fine because <em>oh my god that actually works</em>‽</p><p>Yes it does. Conveniently, arguments are also variables.</p><pre>function createMessage(message) {<br>  return () =&gt; {<br>    return message;<br>  }<br>}<br>const hello = createMessage(&quot;hello&quot;);<br>const goodby = createMessage(&quot;goodbye&quot;);<br>hello() === &quot;hello&quot;;<br>goodbye() === &quot;goodbye&quot;;</pre><h3>More closures</h3><p>A regular and curried (think ‘filled with closures’) add function:</p><pre>// Sad and closure-less<br>function add(x, y) {<br>  return x + y;<br>}<br>add(10, 10) === 20;<br>add(5, 10) == 15;</pre><pre>// Add some closures to it<br>function addC(x) {<br>  return (y) =&gt; x + y<br>}<br>const add10 = addC(10);<br>const add5 = addC(5);<br>add10(10) === 20;<br>add5(10) === 15;</pre><p>A closure that generalizes delaying execution of a function:</p><pre>function delay(fn) {<br>  return () =&gt; {<br>    setTimeout(fn, 500);<br>  }<br>}</pre><pre>function alertImmediate() {<br>  alert(&quot;WARNING&quot;);<br>}<br>const alertDelay = delay(alertImmediate);<br>alertDelay(); // Waits half a second before firing</pre><p>A closure’s power is that you can couple state and code together, then pass them around.</p><h3>Real-world example</h3><p>Async react components are one of the most common places that I use closures. Since components are (mostly) functions, any function defined in a component is probably a closure.</p><pre>import * as React, {useState, useEffect} from &#39;react&#39;;</pre><pre>export default function AsyncComponent() { // Outer function<br>  const [data, setData] = useState(null);</pre><pre>  useEffect(() =&gt; { // First Closure<br>    fetch(&#39;/api/endpoint&#39;).then(() =&gt; { // Second Closure<br>      setData(data); // THIS MAKES IT A CLOSURE.<br>    });<br>  }, [setData]);</pre><pre>  if (!data) {<br>    return &lt;div&gt;Loading&lt;/div&gt;;<br>  }</pre><pre>  return (<br>    &lt;div&gt;Data: {data}&lt;/div&gt;<br>  );<br>}</pre><p>This is a simplified version of a pretty common pattern. In the above code, the only thing coupling component and the function passed into useEffect is setData(data). There are two pretty amazing things happening here</p><ol><li>the First Closure and Second Closure are called outside of the component, and at different times, and</li><li>Second Closure (and therefore First Closure) remember the variable setData, and can use it.</li></ol><h3>Final thoughts</h3><p>Unlike a lot of other coding patterns, closures aren’t often something I think about and decide to use. They’re so simple to write, that they often show up without being invited. However, being comfortable with closures when they show up makes writing JS a lot less intimidating.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9aed70f220" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>