<?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 Griffin Michl on Medium]]></title>
        <description><![CDATA[Stories by Griffin Michl on Medium]]></description>
        <link>https://medium.com/@griffinmichl?source=rss-c7b4efbb309------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*UUwqvE4_B3ADm59D.png</url>
            <title>Stories by Griffin Michl on Medium</title>
            <link>https://medium.com/@griffinmichl?source=rss-c7b4efbb309------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 19:55:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@griffinmichl/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[Asynchronous Javascript: Map]]></title>
            <link>https://medium.com/@griffinmichl/asynchronous-javascript-map-ba9dee36ec9d?source=rss-c7b4efbb309------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba9dee36ec9d</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Griffin Michl]]></dc:creator>
            <pubDate>Wed, 18 May 2016 02:24:50 GMT</pubDate>
            <atom:updated>2016-11-21T18:07:03.312Z</atom:updated>
            <content:encoded><![CDATA[<p>Our goal here is to implement a version of map that will work with asynchronous functions. Map will apply the asynchronous iteratee function to each element in the array and return an array of results. While these async functions may resolve in any order, we want to maintain the order of our original collection in the results array.</p><p>Because map itself is asynchronous, we will give map its own callback. Once every function has resolved, we pass the complete results array to map’s callback. If an error occurs on any element, that error will be passed up to map’s callback and the function will terminate. We will assume all callbacks are in the node error-first style.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/027bc8722742de99bdab485a5e16f892/href">https://medium.com/media/027bc8722742de99bdab485a5e16f892/href</a></iframe><p>Our simple test function is implemented using setTimeout. It doubles first argument when the timeout finishes and passes it to a node-style callback.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bee03e12525dfe1c9369e94bc4c34845/href">https://medium.com/media/bee03e12525dfe1c9369e94bc4c34845/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83b354257cc9f8bd7e9275123c8d7356/href">https://medium.com/media/83b354257cc9f8bd7e9275123c8d7356/href</a></iframe><p>Now lets take a look at one implementation of an asynchronous map.</p><p>First thing’s first, we need to create a results array and a variable to keep track of how many functions are still running. By keeping track of how many functions are running, we’ll know when we’re done mapping.</p><pre>let running = collection.length<br>const results = []</pre><p>Next, we iterate over the collection and apply the iteratee function to each value along with a callback.</p><pre>collection.forEach((value, index) =&gt; <br>  iteratee(value, (err, data) =&gt; {</pre><p>When the callback is invoked, there are two possible results. If the iteratee function throws an error, we want to immediately pass that error to map’s callback and terminate the function.</p><pre>if (err) {<br>  callback(err)<br>  return<br>}</pre><p>Otherwise, we need to update the current state of map. We add add the result of the iteratee function to results array at the same index as in the collection.</p><pre>results[index] = data</pre><p>This point may be a bit tricky.</p><p>First, how do we still have access to `index` when this callback could be called after we’ve already finished iterating through the array? The answer is closures. Functions defined inside functions retain access to the environment in which they were defined. So index inside the callback is the same value as index when the callback was created.</p><p>Second, what if we want to add something to the 2nd index of an empty array? I wasn’t totally sure what would happen when I first wrote this, so I tested it in node.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26f39394d5201073a2f28bdb1cf099fb/href">https://medium.com/media/26f39394d5201073a2f28bdb1cf099fb/href</a></iframe><p>It works just as I hoped. Javascript is smart enough to add `undefined` to each missing element up to the added one and update the length accordingly.</p><p>Now that we’re convinced that adding to the results index will work, we need to decrement the number of running functions. If, after decrementing, no functions are left running, we pass the results array to map’s callback.</p><pre>running--<br>if (running === 0) {<br>  callback(null, results)<br>}</pre><p>And that’s it!</p><p>If you have any feedback on these posts or ideas for future topics, tweet me @griffinmichl.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba9dee36ec9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Debounce in Javascript]]></title>
            <link>https://medium.com/@griffinmichl/implementing-debounce-in-javascript-eab51a12311e?source=rss-c7b4efbb309------2</link>
            <guid isPermaLink="false">https://medium.com/p/eab51a12311e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Griffin Michl]]></dc:creator>
            <pubDate>Tue, 17 May 2016 20:34:16 GMT</pubDate>
            <atom:updated>2016-11-21T18:03:54.520Z</atom:updated>
            <content:encoded><![CDATA[<p>I am generally pretty comfortable with `this`-binding in javascript, but today I managed to confuse myself for a few minutes. I was implementing a simple debounce function for fun and found myself lost in a web of `this`.</p><p>Debouncing makes it so a function can only be executed after a certain amount of time since it was last invoked. For example, “only execute this function if it has been 1000 milliseconds since it was last invoked.”</p><p>A common use case for debouncing is in search bars. We don’t want to make expensive http requests while the user is still typing their query, so we debounce the requesting function and only invoke it once the user has stopped typing.</p><p>Here was my first attempt at implementing debounce.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba317fd68e6180f2ba6b8837251b5aa1/href">https://medium.com/media/ba317fd68e6180f2ba6b8837251b5aa1/href</a></iframe><p>At first glance, this seems to work as expected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93e89b7f65d62cb2171c57e50abd9f4/href">https://medium.com/media/e93e89b7f65d62cb2171c57e50abd9f4/href</a></iframe><p>After taking a look at underscore’s implementation of the same function, I realized that I had made a critical oversight. Namely, what happens when a debounced function is used as a method on an object?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf8944c9f6ecedbd96a707d4d8872f40/href">https://medium.com/media/cf8944c9f6ecedbd96a707d4d8872f40/href</a></iframe><p>That’s not right! Let’s figure out what’s going on here.</p><p>When I invoke `func` inside setTimeout, it is a free function invocation. Free function invocations in javascript have `this` bound to the global scope. However, we want `this` to be bound to the context in which it was invoked (ie. the object amy).</p><p>My first attempt to solve this bug was to get the context when the debounced function is invoked and bind that to the original function via apply.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb143e4e1247237b65c2760802664eac/href">https://medium.com/media/fb143e4e1247237b65c2760802664eac/href</a></iframe><p>`amy.speak` still yields ‘My name is undefined’. The problem now is the lexical-`this` binding of arrow functions. With normal javascript functions, `this` is bound when the function is called. With arrow functions, `this` is bound to the context in which the function is originally created.</p><p>This is an awesome feature, usually. In conforms more to our intuition about how `this` should behave. But we cannot forget about `this` just because we have arrow functions, and this is a perfect example of why.</p><p>`this` is still bound to the global scope in my updated function.</p><pre>debounce(sayHello)</pre><p>When I call `debounce` on `sayHello`, the creation context is the global scope, since debounce is a free-function invokation. Therefore, the arrow function returned from debounce is also bound to the global scope.</p><p>We specifically want `this` to be set at call-time, so an arrow function is the wrong tool entirely. By switching from an arrow function to a traditional anonymous function, we obtain a fully working solution.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfd31eeb2761ed52687c685356c1996c/href">https://medium.com/media/dfd31eeb2761ed52687c685356c1996c/href</a></iframe><p>The moral of the story is that arrow functions don’t absolve you from thinking hard about `this`-binding. In fact, it is more important than ever to have a strong grasp of how `this` behaves in javascript. If I had done the following, no fancy work inside my debounce function could have saved me. `sayHello` would be inextricably bound to the global scope.</p><pre>const sayHello = () =&gt; console.log(&#39;My name is&#39;, this.name)</pre><p>Keep this advice this in mind when using 3rd-party libraries as well. D3 and Mocha come to mind as libraries that can behave unexpectedly if you pass arrow functions as callbacks.</p><p>Arrow functions are great, but you need to know how they work, when to use them, and when to avoid them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab51a12311e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Javascript: Queue]]></title>
            <link>https://medium.com/@griffinmichl/asynchronous-javascript-queue-920828f6327?source=rss-c7b4efbb309------2</link>
            <guid isPermaLink="false">https://medium.com/p/920828f6327</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async-functions]]></category>
            <dc:creator><![CDATA[Griffin Michl]]></dc:creator>
            <pubDate>Mon, 16 May 2016 20:37:35 GMT</pubDate>
            <atom:updated>2016-11-21T18:08:26.920Z</atom:updated>
            <content:encoded><![CDATA[<p>One of my favorite npm libraries is async by <a href="https://github.com/caolan">caolan</a>. It provides an impressive collection of utility functions for working with asynchronous javascript.</p><p>In this blog series, I will reimplement several of the functions found in async. These implementations will be far simpler (and likely less robust) than caolan’s, but I hope they help illuminate what’s going on under-the-hood.</p><p>Queues make for a great place to start.</p><p>Our goal is to implement a factory function called queue. queue will create an object with a concurrency limit. Tasks pushed to the queue will be run concurrently up to the specified limit. If the concurrency limit is reached, tasks will be enqueued until space becomes available for them to run.</p><p>Let’s get started!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ba17796b2cf6d11631a9a7ccf4bc83/href">https://medium.com/media/02ba17796b2cf6d11631a9a7ccf4bc83/href</a></iframe><p>What’s going on here?</p><p>First we define a variable to keep track of how many tasks are currently running.</p><pre>let running = 0</pre><p>Next we create an array to store tasks waiting to be run.</p><pre>const taskQueue = []</pre><p>Before we look at these two private functions, let’s look at the returned object.</p><pre>return { <br>  push: task =&gt; <br>    running &lt; concurrency ? runTask(task) : enqueueTask(task),<br>}</pre><p>The object returned from queue has one method: push. Push has two behaviors. If the number of running tasks is less than the specified concurrency, we can immediately run the pushed task. Otherwise, we need to enqueue the task to be run later. Now let’s see what runTask and enqueueTask do.</p><p>runTask takes a task as argument. First it increments the number of running tasks, because we are about to run the passed-in task. Next it invokes the task. The callback handles the ‘cleanup’ once this task completes. When the task finishes, we need to decrement the number of running tasks. Since we are no longer at the limit of our concurrency with the current task finished, we can check if there are any tasks waiting to be run. If there are, we shift the first-in task off the queue and recursively invoke runTask on it.</p><pre>const runTask = (task) =&gt; {<br>  running++<br>  task(() =&gt; {<br>    running--<br>    if (taskQueue.length &gt; 0) {<br>      runTask(taskQueue.shift())<br>    }<br>  })<br>}</pre><p>enqueueTask is pretty straightforward. It simply takes a task and adds it onto the queue.</p><pre>const enqueueTask = task =&gt; taskQueue.push(task)</pre><p>And there you have it. We’ve implemented a basic asynchronous task runner. Below is an example of how this queue will behave with different concurrencies passed in. You can also play with this implementation here: <a href="http://jsbin.com/bexejofajo/1/edit?js,console">http://jsbin.com/bexejofajo/1/edit?js,console</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c604d0680be43d8c1cdd20389535217/href">https://medium.com/media/0c604d0680be43d8c1cdd20389535217/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=920828f6327" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async/Await with Ternary Operators]]></title>
            <link>https://medium.com/@griffinmichl/async-await-with-ternary-operators-af19f374215?source=rss-c7b4efbb309------2</link>
            <guid isPermaLink="false">https://medium.com/p/af19f374215</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Griffin Michl]]></dc:creator>
            <pubDate>Mon, 21 Mar 2016 22:36:42 GMT</pubDate>
            <atom:updated>2016-03-22T16:07:07.363Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently started making the transition from promises to ES7 async/await functions. I am loving the new feature, but got stuck on a small bug.</p><p>What does the function below wait for?</p><pre>async function doSomeAsyncStuff(flag) {<br>  const result = await flag ? firstPromise() : secondPromise();<br>  return result<br>}</pre><p>I falsely assumed that this would first evaluate the ternary operator, then wait for the corresponding promise. It turns out this will wait for <em>flag</em> to resolve, <strong>then</strong> evaluate the ternary operator. Thus, you need parentheses if you want to choose between two promise returning functions and await the result of the chosen one.</p><pre>async function doSomeAsyncStuff(flag) {<br>  const result = await (flag ? firstPromise() : secondPromise());<br>  return result<br>}</pre><p>This means that you can do some pretty cool stuff with await in async functions. For example,</p><pre>async function doSomeAsyncStuff(flag) {<br>  if (await somePromise()) {<br>    console.log(&#39;Promise resolved to truthy!&#39;)<br>  } else {<br>    console.log(&#39;Promise resolved to falsy&#39;)<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af19f374215" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>