<?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 Brandon Drake on Medium]]></title>
        <description><![CDATA[Stories by Brandon Drake on Medium]]></description>
        <link>https://medium.com/@tomoguisuru?source=rss-7efab8b2d911------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GR8hblYgs89gCGf4fBCEMw.png</url>
            <title>Stories by Brandon Drake on Medium</title>
            <link>https://medium.com/@tomoguisuru?source=rss-7efab8b2d911------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:20:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tomoguisuru/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[Adventures in Interviewing — Response Caching and Memoize FTW]]></title>
            <link>https://medium.com/@tomoguisuru/adventures-in-interviewing-response-caching-and-memoize-ftw-b3be2c648bd7?source=rss-7efab8b2d911------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3be2c648bd7</guid>
            <category><![CDATA[code-interview]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Brandon Drake]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 01:47:31 GMT</pubDate>
            <atom:updated>2025-07-19T01:47:31.901Z</atom:updated>
            <content:encoded><![CDATA[<h3>Adventures in Interviewing — Response Caching and Memoize FTW</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOh7u2CmNZzV5L9a0B6PeQ.png" /></figure><p>In my recent search for employment, I came across a rather interesting coding problem.</p><p>The structure of the question was something like this:</p><p>A function makes a call to another function and returns the results. The task was to create a caching mechanism so that the second function would only be called once unless an error occurred. If an error occurred, the request can be tried again.</p><p>Here’s the example:</p><pre>// ✅ Requirements for getUser():<br>// 1. On the first call:<br>//    - Call fetchUserFromApi() and return the result.<br><br>// 2. If getUser() is called again while the first call is still in progress:<br>//    - Return the same pending promise (so the API isn’t called twice).<br><br>// 3. If the first call fails:<br>//    - Retry the API on the next call (do not cache failed results).<br><br>// 4. Once the API call succeeds:<br>//    - Return the cached user object immediately on all future calls (without calling the API again).<br><br>function fetchUserFromApi() {<br>  console.log(&quot;Fetching user...&quot;);<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      if (Math.random() &gt; 0.2) resolve({ name: &quot;Alice&quot; });<br>      else reject(&quot;API failed&quot;);<br>    }, 500);<br>  });<br>}<br><br>function getUser() {<br>  let user;<br><br>  user = fetchUserFromApi();<br><br>  return user;<br>}</pre><h4>Things Go Wrong</h4><p>Now, there are several ways that this could be solved, but my mind immediately went to adding some variables outside of the function to track either the promise or the cached result. Something like this:</p><pre>let cachedUser = null;<br>let pendingPromise = null;<br><br>async function getUser() {<br>  if (cachedUser) {<br>    console.log(&quot;using cached response&quot;);<br>    return cachedUser;<br>  }<br><br>  if (pendingPromise) {<br>    console.log(&quot;unresolved&quot;);<br>    return pendingPromise;<br>  }<br><br>  try {<br>    pendingPromise = fetchUserFromApi();<br>    cachedUser = await pendingPromise;<br>  } catch (err) {<br>    console.log(&quot;An error has occurred&quot;);<br>    console.error(err);<br>    cachedUser = null;<br>  } finally {<br>    pendingPromise = null;<br>  }<br><br>  return pendingPromise;<br>}</pre><p>We can verify that solution with the following spot check:</p><pre>let user = getUser(); // call without async<br>// Fetching user...<br>// &gt; Promise {&lt;pending&gt;}<br><br>user = getUser();  // verify that the call to fetchUserFromApi isn&#39;t called again<br>// Fetching user...<br><br>...<br><br>// Clearing pendingPromise<br><br>user = await getUser(); <br>// using cached response<br>// &gt; {name: &#39;Alice&#39;}<br><br>await getUser();<br>// using cached response<br>// &gt; {name: &#39;Alice&#39;}</pre><p>This was where my brain first went, and I’d like to say that’s where it stayed, but it didn’t. What I should have done was start asking clarifying questions, but instead, I started overanalyzing the question in my head, making my first and biggest mistake.</p><p>The position I was applying for was heavy on React, so I thought that maybe they wanted to see something that would look React’ish. I my thought process went from debouncing the call to using some kind of memoize function.</p><p>I’ve manually done debounce functions, but it’s been so long ago it might as well have never happened. Memoize, on the other hand, was something I had never tried to manually implement myself. Without a real path in mind, I quickly started typing. This was my second mistake.</p><p>I looked at examples of debouncing calls and realized this isn’t going to work for caching, and then I started looking at memoize implementations and trying to deconstruct them with what little time I had.</p><p>Realizing that I was running out of time and not making much progress with trying to rebuild memoize in ten minutes, I finally started doing what I should have been doing the whole time. Asking questions.</p><h4>Course Correction, But Too Late</h4><p>“Can I reference variables from outside the scope of the function being called?”</p><p>The response wasn’t specific but more along the lines of “it’s up to you, you won’t be penalized for it”.</p><p>Returning to my original idea, I began to scaffold what I posted above, but sadly ran out of time.</p><p>It was over, and I knew I had blown it the second the proctor called time. It’s one of those High School feelings you get after a pop quiz where your mind goes blank the second it hits your desk.</p><h4>A Familiar Solution</h4><p>The proctor was kind enough to share what an acceptable solution would look like, and what did I see?</p><p>This:</p><pre>let cache = null;<br>let inFlight = null;<br><br>async function getUser() {<br>  if (cache) return cache;<br>  if (inFlight) return inFlight;<br><br>  inFlight = fetchUserFromApi()<br>    .then((user) =&gt; {<br>      cache = user;<br>      inFlight = null;<br>      return user;<br>    })<br>    .catch((err) =&gt; {<br>      inFlight = null;<br>      throw err;<br>    });<br><br>  return inFlight;<br>}</pre><p>I was staring at a solution that was almost identical to the one I was originally going to craft. All through school, my teachers often said, “<em>Stay with your original answer, it’s almost always the right one</em>”. It was true then, and it’s still true today.</p><h4>A Lingering Question</h4><p>Now, about a week has passed, but my mind has refused to let this one problem go. I could help but ask myself, “Was the answer the proctor gave, and my original idea for a solution, really ‘right’”? The more I thought about it, the less sure I was.</p><p>Does the solution solve the case given? Yes, I also feel that it’s the wrong solution to the real problem. Let me explain.</p><p>The example question is one that you’ll run into a lot in programming. The problem is that if you start sharing scopes across every function you come across, you’re going to end up with problems that you can’t trace back to their origin.</p><h4>Memoize FTW</h4><p>Revisiting the problem, I constructed a memoize function, taking inspiration from others’ implementations, that would allow for an async call’s results to be cached.</p><pre>function memoizeAsync(fn) {<br>  // Maps are cool, go read about them<br>  const cache = new Map();<br><br>  // The memoized function should also be async<br>  return async function (...args) {<br>    const key = JSON.stringify(args);<br><br>    if (cache.has(key)) {<br>      console.log(&quot;Using cached value&quot;);<br>      return cache.get(key);<br>    }<br><br>    const promise = fn.apply(this, args);<br>    cache.set(key, promise);<br><br>    try {<br>      const resp = await promise;<br>      console.log(&quot;Setting resolved value&quot;);<br>      cache.set(key, resp);<br>    } catch (err) {<br>      console.error(err);<br>      console.log(&quot;Failed, removing from cache&quot;);<br>      cache.delete(key);<br>      throw err;<br>    }<br><br>    return promise;<br>  };<br>}</pre><p>This solution is considerably longer than the original, but it allows for something that the original does not.</p><p>You no longer have to modify the original function to get a cached response!</p><h4>Wrapping It Up</h4><p>Now that we have the memoizeAsync function, let’s apply it to the getUser function.</p><pre>const memoizedGetUser = memoizeAsync(getUser);</pre><p>Next, we replace the getUser call with memoizedGetUser. That’s it, no messing with scoped variables, no extending the function with code it doesn’t need or care about, just a “simple” wrapper function. Don’t want getUser to be cached, just call it directly.</p><p><em>Example:</em></p><pre>// Initial call, leave off the await so we can watch it progress<br>let user = memoizedGetUser();<br>// Fetching user...<br>// &gt; Promise {&lt;pending&gt;}<br><br>// Not resolved yet, let try calling again<br>user = memoizedGetUser();<br>// &gt; Using cached value<br>// Promise {&lt;pending&gt;}<br><br>...<br><br>// Setting resolved value<br><br>// Request what do we have?<br>user<br>// Promise {&lt;fulfilled&gt;: {…}}<br><br>// resolve the promise and get the value<br>user = await user;<br>// &gt; {name: &#39;Alice&#39;}<br><br>// Call the memoized again and get the same value as before<br>user = await memoizedGetUser();<br>// &gt; {name: &#39;Alice&#39;}</pre><p>Plus, as an added bonus, this also allows us to cache other functions that might share the same basic setup whenever we want and to cache different responses for the same function based on the parameters we pass in.</p><h4>Final Thoughts</h4><p>This is a solution I’m happy with for two reasons. First, the original function was treated as a “black box,” and we built a tool that can be used in other parts of a codebase.</p><p>What are your thoughts? Was the memoize route too much, or do you agree with me that it follows best practices? Let me know your feelings below, or how this solution could be improved further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3be2c648bd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy Loading With Ember Power Select Using Contextual Components]]></title>
            <link>https://medium.com/@tomoguisuru/lazy-loading-with-ember-power-select-using-composable-components-564af32321bf?source=rss-7efab8b2d911------2</link>
            <guid isPermaLink="false">https://medium.com/p/564af32321bf</guid>
            <category><![CDATA[emberjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ember-power-select]]></category>
            <category><![CDATA[contextual-components]]></category>
            <category><![CDATA[ember]]></category>
            <dc:creator><![CDATA[Brandon Drake]]></dc:creator>
            <pubDate>Thu, 17 Aug 2017 20:52:29 GMT</pubDate>
            <atom:updated>2017-08-17T21:08:26.409Z</atom:updated>
            <content:encoded><![CDATA[<p>Lazy Loading With Ember Power Select Using Contextual Components</p><p><a href="http://www.ember-power-select.com/">Ember Power Select</a></p><p>Out of the box, Power Select has a lot to offer. You can customize in just about any way that you can think of and has been one of my favorite community plugins to date. Even the way the code is written is amazing.</p><p>When I first started writing plugins and components for Teem, Power Select was the main inspiration for how I now organize and design my components. Making extensible and dynamic components is important into todays ecosystem. Plus, it’s just more efficient.</p><p>Power Select is amazingly forward thinking in how it was design. If there is something that you want to customize, all you have to do is plug in your own component to get rolling.</p><h3>Infinite Scrolling with Power Select</h3><p>First, we need to decide how we’re going to lazy-load our list. I decided that the best way to do it for my needs was to put a element at the end of the list that would trigger a load event whenever became visible to the user. This allows us to only load a small portion of the data upfront but still allow the user to scroll through everything if they feel the need to do so.</p><p>Looking over the API for Ember Power Select, <a href="http://www.ember-power-select.com/docs/api-reference">http://www.ember-power-select.com/docs/api-reference</a>, we see that component we’re going to want to replace is called <strong>optionsComponent</strong>.</p><p>Let’s generate a new component, ember g component lazy-options, and copy the existing options template code intotemplates/components/lazy-options.hbs</p><pre>&lt;!--  <a href="https://github.com/cibernox/ember-power-select/blob/master/addon/templates/components/power-select/options.hbs">https://github.com/cibernox/ember-power-select/blob/master/addon/templates/components/power-select/options.hbs</a> --&gt;<br>{{#if select.loading}}<br>  {{#if loadingMessage}}<br>    &lt;li class=&quot;ember-power-select-option ember-power-select-option--loading-message&quot; role=&quot;option&quot;&gt;{{loadingMessage}}&lt;/li&gt;<br>  {{/if}}<br>{{/if}}<br>{{#each options as |opt index|}}<br>  {{#if (ember-power-select-is-group opt)}}<br>    {{#component groupComponent<br>        group=(readonly opt)<br>        select=(readonly select)<br>        extra=(readonly extra)<br>      }}<br>      {{#component optionsComponent<br>        options=(readonly opt.options)<br>        select=(readonly select)<br>        groupIndex=(concat groupIndex index &quot;.&quot;)<br>        optionsComponent=(readonly optionsComponent)<br>        groupComponent=(readonly groupComponent)<br>        extra=(readonly extra)<br>        role=&quot;group&quot;<br>        class=&quot;ember-power-select-options&quot; as |option|}}<br>        {{yield option select}}<br>      {{/component}}<br>    {{/component}}<br>  {{else}}<br>    &lt;li class=&quot;ember-power-select-option&quot;<br>      aria-selected=&quot;{{ember-power-select-is-selected opt select.selected}}&quot;<br>      aria-disabled={{ember-power-select-true-string-if-present opt.disabled}}<br>      aria-current=&quot;{{eq opt select.highlighted}}&quot;<br>      data-option-index=&quot;{{groupIndex}}{{index}}&quot;<br>      role=&quot;option&quot;&gt;<br>      {{yield opt select}}<br>    &lt;/li&gt;<br>  {{/if}}<br>{{/each}}</pre><p>and then we’re going to modify out components/lazy-options.js to extend the original options component, components/options.js, from Power Select by importing it</p><pre><strong>import </strong>Ember <strong>from </strong>&#39;ember&#39;;<br><br><strong>import </strong>PSOptionsComponent <strong>from </strong>&#39;ember-power-select/components/power-select/options&#39;;</pre><pre>const LazyOptionsComponent = PSOptionsComponent.extend({<br>  // TODO<br>});</pre><pre>export default LazyOptionsComponent;</pre><p>At this point, we should be able to specify the optionsComponent property as our new component and have the exact same functionality as before.</p><h3>Customizing the Template</h3><p>Per the design, we need an element at the bottom that shows when we have more items to load. We will add the following code to the bottom of our template, template/components/lazy-options.hbs, to accomplish this</p><pre>{{#<strong>if </strong>(<strong>or isLoading select</strong>.<strong>loading</strong>)}}<br>  Loading...<br>{{<strong>else if canLoadMore</strong>}}<br>  &lt;li class=&quot;ember-power-select-option ember-power-select-option--load-more&quot; {{<strong>action loadMore</strong>}}&gt;<br>    Load More<br>  &lt;/li&gt;<br>{{/<strong>if</strong>}}</pre><p>This block of code just looks to see if we can load more via canLoadMore and shows a loading message, Loading..., if we’re currently loading data. Even though we want this to trigger automatically when it comes into view, an action has been included as a fallback.</p><h3>Extending jQuery</h3><p>Next we need to extend jQuery with a custom function checkInView. I’ve placed mine in utils/extensions/jquery.js and have called it checkInView</p><pre><strong>import </strong>Ember <strong>from </strong>&#39;ember&#39;;<br><br><strong>const </strong>{<br>  $,<br>} = Ember;<br><br><strong>function </strong>checkInView() {<br>  <strong>if </strong>($.fn.checkInView) { <strong>return</strong>; }<br><br>  $.fn.checkInView = <strong>function</strong>(partial = <strong>false</strong>) {<br>    <strong>const </strong>elem = <strong>this</strong>;<br><br>    <strong>if </strong>(!elem.length) { <strong>return false</strong>; }<br><br>    <strong>const </strong>container = elem.parent();<br>    <strong>const </strong>contHeight = container.height();<br>    <strong>const </strong>contTop = container.scrollTop();<br>    <strong>const </strong>contBottom = contTop + contHeight;<br><br>    <strong>const </strong>elemTop = elem.offset().top - container.offset().top;<br>    <strong>const </strong>elemBottom = elemTop + elem.height();<br><br>    <strong>const </strong>isTotal = elemTop &gt;= 0 &amp;&amp; elemBottom &lt;= contHeight;<br>    <strong>const </strong>isPart = (elemTop &lt; 0 &amp;&amp; elemBottom &gt; 0  || elemTop &gt; 0 &amp;&amp; elemTop &lt;= container.height()) &amp;&amp; partial;<br><br>    <strong>return  </strong>isTotal  || isPart;<br>  };<br>}<br><br><strong>export </strong>{ checkInView };</pre><p>Now need to include the extension it in an initializer, initializers/jquery-extensions.js</p><pre><strong>import </strong>{ checkInView } <strong>from </strong>&#39;../utils/extensions/jquery&#39;;<br><br><strong>export function </strong>initialize() {<br>  // Add jQuery extension calls here<br>  checkInView();<br>}<br><br><strong>export default </strong>{<br>  name:       &#39;jq-extensions&#39;,<br>  initialize: initialize<br>};</pre><h3>Triggering the Auto-Load</h3><p>With our newly create jQuery extension, we’re ready to trigger the load event automatically. We will return to our component and update it with the following</p><pre>//component/lazy-options.js<br>import Ember from &#39;ember&#39;;</pre><pre>import PSOptionsComponent from &#39;ember-power-select/components/power-select/options&#39;;</pre><pre>const {<br>  $,<br>  assert,<br>  get,<br>} = Ember;</pre><pre>const OptionsComponent = PSOptionsComponent.extend({<br>  canLoadMore: false,</pre><pre>init() {<br>    this._super(...arguments); </pre><pre>assert(&#39;&lt;component:infinite-options&gt;: You must provide a closure action name `loadMore`&#39;, get(this, &#39;loadMore&#39;) &amp;&amp; typeof get(this, &#39;loadMore&#39;) === &#39;function&#39;);<br>  },</pre><pre>didInsertElement() {<br>    this._super(...arguments);<br>    const checkVisibility = () =&gt; {<br>      if ($(this.element).find(&#39;.ember-power-select-option--load-more&#39;).checkInView(true)) {<br>        const loadMore = get(this, &#39;loadMore&#39;);</pre><pre>return loadMore();<br>      }<br>    };</pre><pre>$(this.element).on(&#39;scroll&#39;, () =&gt; checkVisibility());<br>  },</pre><pre>willDestroyElement() {<br>    this._super(...arguments);</pre><pre>$(this.element).off(&#39;scroll&#39;);<br>  }</pre><pre>});</pre><pre>export default OptionsComponent;</pre><p>in the init method, we’re checking to make sure we have a closure action name loadMore that we’ll use when the loadMore element comes into view. In the didInsertElement method, we attach on event to scroll. This will check to see if the loadMore element has come into view yet. The checkVisibility is where we will be triggering the loadMore from if the element is visible. Just to be safe and make sure we clean up after ourselves, we also add an off event so that we don’t accidentally load records when the options aren’t showing.</p><h3>Using The Component</h3><p>Since API tend to use different pagination schemas, I’ve left that part to the consumer to handle rather than bake it into our component. This leaves us with a more flexible API on the component it’s self since it only require the user to provide a maximum of three properties, loadMore, canLoadMore, and isLoading.</p><p>Basic implementation will look something like this in your app</p><pre>{{#power-select optionsComponent=(component &#39;lazy-options&#39;<br>                                            loadMore=(perform task__loadMore)<br>                                            isLoading=isLoading<br>                                            canLoadMore=canLoadMore<br>                )<br>                options=colors<br>                selected=selectedColor<br>                onchange=(action (mut selectedColor))<br>                as |option|}}<br>            {{option}}<br>{{/power-select}}</pre><p>Here I’m using Ember Concurrency but you can also use closure actions</p><h3>Demo Time</h3><p>Here is a working, semi real-world, Twiddle of how you’d use the lazy-options component in your own code.</p><p><a href="https://ember-twiddle.com/e5b38cd212dbef20249f366790f467e1">Ember Twiddle</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=564af32321bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>