<?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"><channel><title><![CDATA[joakimbeng]]></title><description><![CDATA[Let&#39;s code a better tomorrow...]]></description><link>https://joakim.beng.se/blog</link><generator>Jiffy RSS generator</generator><lastBuildDate>Thu, 07 Dec 2023 20:15:48 GMT</lastBuildDate><atom:link href="https://joakim.beng.se/blog/rss.xml" rel="self" type="application/rss+xml"/><author><![CDATA[Joakim Carlstein]]></author><ttl>60</ttl><item><title><![CDATA[A memoizer like React&#39;s useMemo in 20 lines]]></title><description><![CDATA[<p>This is another post in my series of ”20 lines of code” posts. For the previous ones see:</p>
<ul>
<li><a href="https://joakim.beng.se/blog/posts/a-javascript-router-in-20-lines.html">A JavaScript router in 20 lines</a></li>
<li><a href="https://joakim.beng.se/blog/posts/a-javascript-test-runner-in-20-lines.html">A JavaScript test runner in 20 lines</a></li>
</ul>
<h2 id="whats-memoization-and-whats-special-about-reacts-usememo">What’s memoization and what’s special about React’s useMemo?</h2>
<p><a href="https://en.wikipedia.org/wiki/Memoization">Memoization</a>, in short, is used to cache function results given its input to avoid expensive computations. React&#39;s <a href="https://reactjs.org/docs/hooks-reference.html#usememo"><code>useMemo</code></a> is a special kind of memoization function as it does not re-run the “expensive computation” based on its input but on an explicit list of dependencies, which should be set to all variables that the memoized function depends on/uses.</p>
<p>Let’s demonstrate the difference with an example...</p>
<p><strong>Example of memoization tracking its input:</strong></p>
<pre><code class="language-javascript"><span class="hljs-keyword">let</span> a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> expensive = <span class="hljs-function">(<span class="hljs-params">b</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> a.reduce(<span class="hljs-function">(<span class="hljs-params">sum, val</span>) =&gt;</span> sum * b + val, <span class="hljs-number">0</span>);
};
<span class="hljs-keyword">const</span> expensiveMemoized = memoize(expensive);
expensiveMemoized(<span class="hljs-number">2</span>);
<span class="hljs-comment">// =&gt; 12 (not in cache)</span>
expensiveMemoized(<span class="hljs-number">2</span>);
<span class="hljs-comment">// =&gt; 12 (from cache)</span>
a = [...a, <span class="hljs-number">4</span>];
expensiveMemoized(<span class="hljs-number">2</span>);
<span class="hljs-comment">// =&gt; 12 (from cache, because &quot;a&quot; is not part of the function&#x27;s input)</span></code></pre>
<p><strong>Example using useMemo:</strong></p>
<p>(ignore the fact that <code>useExpensive</code> should be used within a component or other hook)</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> useExpensive = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> result = useMemo(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">return</span> a.reduce(<span class="hljs-function">(<span class="hljs-params">sum, val</span>) =&gt;</span> sum * b + val, <span class="hljs-number">0</span>);
  }, [a, b]);

  <span class="hljs-keyword">return</span> result;
};

<span class="hljs-keyword">let</span> a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
useExpensive(a, <span class="hljs-number">2</span>);
<span class="hljs-comment">// =&gt; 12 (not in cache)</span>
useExpensive(a, <span class="hljs-number">2</span>);
<span class="hljs-comment">// =&gt; 12 (in cache)</span>
a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
useExpensive(a, <span class="hljs-number">2</span>);
<span class="hljs-comment">// =&gt; 20 (not in cache)</span></code></pre>
<p>As you can see the <code>useMemo</code> function re-runs the expensive function when any of its dependencies (<code>a</code> and <code>b</code> in this case) changes. Another special thing about React’s <code>useMemo</code> is the fact that it memoizes the function result per component instance that uses it, i.e. the following code runs the ”expensive calculation” twice even though the parameters are the same and they get the same result:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> Comp = <span class="hljs-function">(<span class="hljs-params">{ a, b }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> result = useExpensive(a, b);
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>One: {result}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};

<span class="hljs-keyword">const</span> a = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Comp</span> <span class="hljs-attr">a</span>=<span class="hljs-string">{a}</span> <span class="hljs-attr">b</span>=<span class="hljs-string">{2}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Comp</span> <span class="hljs-attr">a</span>=<span class="hljs-string">{a}</span> <span class="hljs-attr">b</span>=<span class="hljs-string">{2}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};</code></pre>
<p>The same is also true if two different components uses the same hook.</p>
<p>Enough about the existing <code>useMemo</code> and let’s write some code to built it ourselves!</p>
<h2 id="lets-make-our-own-memoization-hook">Let’s make our own memoization hook</h2>
<p>The key part of memoization is to know when to discard an old value and re-run the memoized function. To do that we have to check if any of the specified dependencies have changed, which can be done using the following naive approach:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">let</span> lastDeps = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">let</span> lastValue;

<span class="hljs-keyword">const</span> useMemo = <span class="hljs-function">(<span class="hljs-params">func, deps = []</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (lastDeps === <span class="hljs-literal">null</span> || deps.some(<span class="hljs-function">(<span class="hljs-params">dep, i</span>) =&gt;</span> dep !== lastDeps[i])) {
    lastDeps = deps;
    <span class="hljs-keyword">return</span> (lastValue = func());
  }
  <span class="hljs-keyword">return</span> lastValue;
};</code></pre>
<p>I said “naive” because this implementation has a big drawback - it can’t be reused! E.g:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> a = <span class="hljs-number">4</span>;
useMemo(<span class="hljs-function">() =&gt;</span> a ** <span class="hljs-number">2</span>, [a]); <span class="hljs-comment">// =&gt; 16</span>
useMemo(<span class="hljs-function">() =&gt;</span> a * <span class="hljs-number">2</span>, [a]); <span class="hljs-comment">// =&gt; 16, because the dependencies hasn&#x27;t changed, but our function has...</span></code></pre>
<p>We therefore have to track the function somehow. A simple solution would be to add the function as a dependency and compare it as well:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">let</span> lastDeps = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">let</span> lastValue;

<span class="hljs-keyword">const</span> useMemo = <span class="hljs-function">(<span class="hljs-params">func, deps = []</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> newDeps = [func, ...deps];
  <span class="hljs-keyword">if</span> (lastDeps === <span class="hljs-literal">null</span> || newDeps.some(<span class="hljs-function">(<span class="hljs-params">dep, i</span>) =&gt;</span> dep !== lastDeps[i])) {
    lastDeps = newDeps;
    <span class="hljs-keyword">return</span> (lastValue = func());
  }
  <span class="hljs-keyword">return</span> lastValue;
};</code></pre>
<p>That will solve our previous issue, but will cause another... Using this implementation of <code>useMemo</code> inside a component will trigger a re-run of the function on every render, for instance a component such as:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> Comp = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> result = useMemo(<span class="hljs-function">() =&gt;</span> <span class="hljs-number">1000</span> ** <span class="hljs-number">5</span>, []);
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{result}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};</code></pre>
<p>Every time <code>Comp</code> is rendered the <code>() =&gt; 1000 ** 5</code> function is recreated, which means it will never make our comparison with <code>newDeps</code> be true and the function will be re-run all the time.</p>
<h3 id="tracking-the-memoized-function">Tracking the memoized function</h3>
<p>To solve this we need a way to see if a function is unchanged without relying on its reference, as the reference is changed on every render. One approach would be to convert the function to a string and see if the string has changed, but I’m afraid that will only work in simple scenarios. Consider the following:</p>
<pre><code class="language-javascript"><span class="hljs-comment">// in Component.js:</span>
<span class="hljs-keyword">const</span> doSomething = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-number">1000</span> ** <span class="hljs-number">5</span>;
};

<span class="hljs-keyword">const</span> result = useMemo(<span class="hljs-function">() =&gt;</span> doSomething(), []); <span class="hljs-comment">// (1)</span>

<span class="hljs-comment">// in OtherComponent.js:</span>
<span class="hljs-keyword">const</span> doSomething = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-number">1000</span> + <span class="hljs-number">5</span>;
};

<span class="hljs-keyword">const</span> result = useMemo(<span class="hljs-function">() =&gt;</span> doSomething(), []); <span class="hljs-comment">// (2)</span></code></pre>
<p>As you can see in the snippet above the statements <strong>(1)</strong> and <strong>(2)</strong> looks the same and would be the same if we cast the memoized functions to strings, even though <code>doSomething</code> is different in the two files. So we need something else that we can use as a stable reference to our memoized functions, even when they are recreated on every render.</p>
<p>React has solved this by tracking the order of called hooks per component instance, which is exactly why there are <a href="https://reactjs.org/docs/hooks-rules.html">Rules of Hooks</a>, because if that order would change the results would be mixed and unexpected. The solution I&#39;ve come up with is different and thanks to that will have some less strict rules as you’ll see.</p>
<p>My solution is based on the fact that there is one thing that’s always constant for each invocation of <code>useMemo</code> in your code - its call site, i.e. the place in the code like the file, line and column number from where the function is called. So how can we get that information without any extra tooling? (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller"><code>function.caller</code></a>is deprecated and doesn’t work anymore)</p>
<p>A simple trick to get a function’s call site is to get hold of a stack trace and get the information from there (see potential caveats of this approach in the bottom of the post).</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> getCallSite = <span class="hljs-function">(<span class="hljs-params">depth</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { stack } = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">&quot;getting call site&quot;</span>);
  <span class="hljs-keyword">return</span> stack.split(<span class="hljs-string">&quot;\n&quot;</span>)[depth];
};

<span class="hljs-keyword">const</span> A = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(getCallSite(<span class="hljs-number">2</span>));
};
<span class="hljs-keyword">const</span> B = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(getCallSite(<span class="hljs-number">2</span>));
};

A();
<span class="hljs-comment">// at A (.../index.js:7:15)</span>
B();
<span class="hljs-comment">// at B (.../index.js:10:15)</span></code></pre>
<p>I’m passing a <code>depth</code> of <code>2</code> because the first line of a stack trace (index = 0) is usally the error message (“getting call site&quot; in this case), the second line (index = 1) is the actual <code>getCallSite</code> function and in this case the third line (index = 2) is our functions <code>A</code> and <code>B</code> .</p>
<p>Let’s use this new <code>getCallSite</code> function to improve the <code>useMemo</code> implementation. You&#39;ll notice in the code that I&#39;ve increased the depth to <code>3</code> because here the third line of the stack trace (index = 2) corresponds to our <code>useMemo</code> function and we care for from where it was called and not declared so we have to check the next line of the stack trace:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> lastDeps = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();
<span class="hljs-keyword">const</span> lastValue = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();

<span class="hljs-keyword">const</span> getCallSite = <span class="hljs-function">(<span class="hljs-params">depth</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { stack } = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">&quot;getting call site&quot;</span>);
  <span class="hljs-keyword">return</span> stack.split(<span class="hljs-string">&quot;\n&quot;</span>)[depth];
};

<span class="hljs-keyword">const</span> useMemo = <span class="hljs-function">(<span class="hljs-params">func, deps</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> callSite = getCallSite(<span class="hljs-number">3</span>);
  <span class="hljs-keyword">if</span> (!lastDeps.has(callSite) || lastDeps.get(callSite).some(<span class="hljs-function">(<span class="hljs-params">dep, i</span>) =&gt;</span> dep !== deps[i])) {
    lastDeps.set(callSite, deps);
    <span class="hljs-keyword">const</span> value = func();
    lastValue.set(callSite, value);
    <span class="hljs-keyword">return</span> value;
  }
  <span class="hljs-keyword">return</span> lastValue.get(callSite);
};</code></pre>
<p>One could think that we would be done here, but this version still has some issues. The problem is that the cache only stores one value per call site, which means that a scenario like the following will never re-use anything from the cache:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> Child = <span class="hljs-function">(<span class="hljs-params">{ val }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> result = useMemo(<span class="hljs-function">() =&gt;</span> val ** <span class="hljs-number">5</span>, [val]);
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{result}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};

<span class="hljs-keyword">const</span> Parent = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Child</span> <span class="hljs-attr">val</span>=<span class="hljs-string">{1}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Child</span> <span class="hljs-attr">val</span>=<span class="hljs-string">{2}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};</code></pre>
<p>On first render when <code>&lt;Child val={1} /&gt;</code> is rendered there&#39;s nothing in the cache so the memoized function will be run and when <code>&lt;Child val={2} /&gt;</code> is rendered there&#39;s nothing in the cache for <code>val=2</code> so the memoized function will be run again. On the next render when <code>&lt;Child val={1} /&gt;</code> is rendered again there is nothing in the cache for <code>val=1</code> so the memoized function is re-run, and so on…</p>
<h3 id="caching-multiple-values">Caching multiple values</h3>
<p>To remedy this issue we’ll have to store multiple values per call site. Instead of using only the call site as the key for <code>lastValue</code> we&#39;ll generate a key from both the call site and the current dependencies.</p>
<p>How do we generate a good lookup key out of an array of dependencies? Would <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify">JSON.stringify()</a> do? No, it can&#39;t handle functions or circular data structures for instance. But by using its <code>replacer</code> option and a neat use of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap">WeakMap</a> we get a memory efficient key generator:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">let</span> keys = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;
<span class="hljs-keyword">const</span> getKeySet = <span class="hljs-function">(<span class="hljs-params">arr</span>) =&gt;</span>
  <span class="hljs-built_in">JSON</span>.stringify(arr, <span class="hljs-function">(<span class="hljs-params">_, val</span>) =&gt;</span> {
    <span class="hljs-comment">// val !== arr -- because we ignore the dependency array itself</span>
    <span class="hljs-comment">// typeof val === &quot;object&quot; -- because only objects can be used as keys in a WeakMap</span>
    <span class="hljs-comment">// val !== null -- because typeof null === &quot;object&quot; :P</span>
    <span class="hljs-keyword">if</span> (val !== arr &amp;&amp; <span class="hljs-keyword">typeof</span> val === <span class="hljs-string">&quot;object&quot;</span> &amp;&amp; val !== <span class="hljs-literal">null</span>) {
      <span class="hljs-keyword">if</span> (!keys.has(val)) {
        keys.set(val, <span class="hljs-string">`$$obj<span class="hljs-subst">${i++}</span>`</span>);
      }
      <span class="hljs-keyword">return</span> keys.get(val);
    }
    <span class="hljs-keyword">return</span> val;
  });

<span class="hljs-comment">// Example usage:</span>
<span class="hljs-keyword">const</span> a = {};
<span class="hljs-keyword">const</span> b = {};
getKeySet([a, <span class="hljs-number">10</span>]); <span class="hljs-comment">// [&quot;$$obj0&quot;, 10]</span>
getKeySet([b, <span class="hljs-number">10</span>]); <span class="hljs-comment">// [&quot;$$obj1&quot;, 10]</span>
getKeySet([<span class="hljs-literal">true</span>, b, a]); <span class="hljs-comment">// [true, &quot;$$obj1&quot;, &quot;$$obj0&quot;]</span></code></pre>
<p>Let’s use this key generator in our <code>useMemo</code> implementation:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> values = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>();
<span class="hljs-keyword">const</span> keys = <span class="hljs-keyword">new</span> <span class="hljs-built_in">WeakMap</span>();
<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>;
<span class="hljs-keyword">const</span> getKeySet = <span class="hljs-function">(<span class="hljs-params">arr = []</span>) =&gt;</span>
  <span class="hljs-built_in">JSON</span>.stringify(arr, <span class="hljs-function">(<span class="hljs-params">_, val</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (val !== arr &amp;&amp; <span class="hljs-keyword">typeof</span> val === <span class="hljs-string">&quot;object&quot;</span> &amp;&amp; val) {
      <span class="hljs-keyword">if</span> (!keys.has(val)) {
        keys.set(val, <span class="hljs-string">`$$obj<span class="hljs-subst">${i++}</span>`</span>);
      }
      <span class="hljs-keyword">return</span> keys.get(val);
    }
    <span class="hljs-keyword">return</span> val;
  });
<span class="hljs-keyword">const</span> getCallSite = <span class="hljs-function">(<span class="hljs-params">depth</span>) =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">&quot;getting call site&quot;</span>).stack.split(<span class="hljs-string">&quot;\n&quot;</span>)[depth];
<span class="hljs-keyword">const</span> useMemo = <span class="hljs-function">(<span class="hljs-params">func, deps</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> key = <span class="hljs-string">`<span class="hljs-subst">${getCallSite(<span class="hljs-number">3</span>)}</span>|<span class="hljs-subst">${getKeySet(deps)}</span>`</span>;
  <span class="hljs-keyword">if</span> (!values.has(key)) {
    values.set(key, func());
  }
  <span class="hljs-keyword">return</span> values.get(key);
};</code></pre>
<p><strong>That’s it, our own <code>useMemo</code> hook is complete!</strong> I made the <code>getCallSite</code> function a one-liner to land on a total of exactly 20 lines of code as I promised (alright 21 after <a href="https://prettier.io">Prettier</a> has done its deal).</p>
<h2 id="pros-and-cons-over-reacts-usememo">Pros and cons over React’s useMemo</h2>
<p>One downside of this solution is that it can be expensive performance-wise to generate a stack trace, although under normal circumstances it should take less than a millisecond. Another thing about getting the call site is that the stack trace format is not standardized, even though most browsers have a similar format, so our <code>getCallSite</code> function can either crash, in case <code>error.stack</code> is not a string, or give the wrong result (see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/Stack">Error.prototype.stack</a> for more info).</p>
<p>Another caveat is that cached values are never cleared, so unused values for key sets that don’t even exist anymore because of garbage collected objects will still be stored in memory. Switching the <code>const values = new Map()</code> to a Least Recently Used Cache (e.g. <a href="https://www.npmjs.com/package/lru-cache">lru-cache</a> ) would solve this in a configurable manner.</p>
<p>There is also a potential issue if a dependency is a string with a value colliding with an existing <code>$$objN</code> key, a fix for that would be to replace the outer <code>JSON.stringify</code> with an ordinary <code>Array.map</code> and only stringify the non-objects like so:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">const</span> getKeySet = <span class="hljs-function">(<span class="hljs-params">arr = []</span>) =&gt;</span>
  arr
    .map(<span class="hljs-function">(<span class="hljs-params">val</span>) =&gt;</span> {
      <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> val === <span class="hljs-string">&quot;object&quot;</span> &amp;&amp; val) {
        <span class="hljs-keyword">if</span> (!keys.has(val)) {
          keys.set(val, <span class="hljs-string">`$$obj<span class="hljs-subst">${i++}</span>`</span>);
        }
        <span class="hljs-keyword">return</span> keys.get(val);
      }
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">JSON</span>.stringify(val);
    })
    .join(<span class="hljs-string">&quot;,&quot;</span>);</code></pre>
<p>On the plus side, as I mentioned earlier, this solution doesn’t have the same strict rules as React’s hooks has, for instance this <code>useMemo</code> can be used both <em>outside components and conditionally</em>, thanks to the fact that the call site is constant even for conditional calls.</p>
<p>Another advantage is that memoized values will be shared across component instances as long as they have the same dependencies.</p>
<h2 id="final-words">Final words</h2>
<p>I hope you enjoyed this journey of writing a <code>useMemo</code> hook from scratch, I know I did! You should know that the hook has not been battle tested in a real app so there could be other issues with it apart from the small downsides in the previous section.</p>
<p>If you have any questions, suggestions or anything else don’t hesitate to reach out!</p>
<p><strong>Until next time!</strong> / <a href="https://twitter.com/joakimbeng">@joakimbeng</a></p>
]]></description><link>https://joakim.beng.se/blog/posts/a-memoizer-like-reacts-usememo-in-20-lines.html</link><guid isPermaLink="false">169c21f6-baf8-41d1-8861-61e05f46ac3b</guid><dc:creator><![CDATA[Joakim Carlstein]]></dc:creator><pubDate>Thu, 11 Feb 2021 20:39:00 GMT</pubDate></item><item><title><![CDATA[Two of the most important rules when programming]]></title><description><![CDATA[<p>The following rules are two of the most important rules to follow when writing code in my opinion. They apply both if you’re in a team or in a one-person project.</p>
<h2 id="rule-1---write-for-the-next-developer">Rule 1 - Write for the next developer</h2>
<p>The next developer reading your code can either be yourself or someone else, make that person a great service by making your code readable. Usually you read more code than you write, so if you have to write some more code to make it more readable that’s worth it.</p>
<h3 id="some-practical-tips-on-writing-more-readable-code">Some practical tips on writing more readable code</h3>
<ul>
<li>Use a linter with some recommended/common configuration, for instance <a href="https://eslint.org">Eslint</a> and <a href="https://www.npmjs.com/package/eslint-config-airbnb">eslint-config-airbnb</a></li>
<li>Use code formatting tools like <a href="https://prettier.io">Prettier</a></li>
<li>Use linting and code formatting rules that yields smaller git diffs, e.g.§§ always trailing commas and always parentheses around function parameters</li>
<li>Never write one-line if statements, i.e. those without <code>{</code> and <code>}</code></li>
<li>Prefer if statements before nested ternary operators</li>
<li>Never use negated or negative words in variable names, i.e. prefer <code>isEnabled</code> and <code>isValid</code> over <code>isDisabled</code> and <code>isWrong</code>. Why? Because sooner or later you’ll end up with statements that take some time to digest like: <code>if (isInvalid !== true &amp;&amp; !disallowedToSave) { ...</code></li>
<li>If you still think your code isn’t perfect from a reader’s perspective, or you don’t have the time or mind to do it right now, add some automated tests that verifies the functionality and perhaps enhance the code with some descriptive <a href="https://jsdoc.app">JSDoc</a> comments</li>
</ul>
<p>The focus you should have when improving readability of code is primarily so that the next developer understands your code faster, in case that person has to debug it.</p>
<h2 id="rule-2---leave-the-code-better-than-when-you-found-it">Rule 2 - Leave the code better than when you found it</h2>
<p>Also known as the “scouts rule”. Improving the code quality in a large code base all at once is very time consuming. It’s cheaper and easier to aim for “Eventual Good Code Quality”, i.e. while you’re adding some new feature or fixing a bug in a file take the time to also improve the code quality of that same file. You don’t have to fix all issues at once, one change for the better is better than none.</p>
<h3 id="some-quick-wins-when-improving-code-quality">Some quick wins when improving code quality</h3>
<ul>
<li>Rename variables or functions for clarity and easing the reading experience</li>
<li>When you’re debugging some hard to read code, once you understand it, add automated tests for it to aid the next developer</li>
<li>Refactor hard to follow statements or conditions into separate functions with descriptive names, e.g. instead of <code>if (name &amp;&amp; name.length &gt; 0 &amp;&amp; hasAccess(userId, parentId)) {</code> do <code>if (canSave()) {</code></li>
<li>Remove unused code</li>
</ul>
<h2 id="conclusion">Conclusion</h2>
<p><em>Readability, readability, readability!</em> Readable code is more important than fast written code.</p>
<p>If you keep <strong>Rule 1</strong> in mind all the time and apply those guidelines when you’re changing old code you get <strong>Rule 2</strong> for free.</p>
<p><a href="https://twitter.com/joakimbeng">Follow me on Twitter</a> for more insights like this!</p>
]]></description><link>https://joakim.beng.se/blog/posts/two-important-rules-when-programming.html</link><guid isPermaLink="false">8ff62484-4579-42a5-b3be-ea52c7c69306</guid><dc:creator><![CDATA[Joakim Carlstein]]></dc:creator><pubDate>Wed, 27 Jan 2021 08:41:00 GMT</pubDate></item><item><title><![CDATA[Choosing a web app tech stack - part 1: the programming language]]></title><description><![CDATA[<p>As I said in my <a href="https://joakim.beng.se/blog/posts/building-an-app-i-need.html">previous post</a> I’m about to build a new web app, and the first thing I will do is to decide what programming language to use. Previously you didn’t have much choice as to what language to pick, regarding the frontend anyway, but with the <a href="https://caniuse.com/wasm">wide support for WebAssembly</a> and languages that can compile to it theese days you now have plenty to choose from.</p>
<p>The big benefit, as I see it, with using WebAssembly for the frontend is that you can use the same language for both the frontend and the backend.</p>
<h2 id="should-i-go-for-high-developer-satisfaction">Should I go for high developer satisfaction?</h2>
<p>At first I was thinking about writing the app in <a href="https://www.rust-lang.org">Rust</a> so I spent a lot of time last summer reading the <a href="https://doc.rust-lang.org/book/">Rust Book</a>. I was leaning towards Rust mainly because of the <a href="https://insights.stackoverflow.com/survey/2020#technology-most-loved-dreaded-and-wanted-languages-loved">high developer satisfaction</a> with it and its high performance.</p>
<p>For a while there I really had made up my mind. I was going to build my next app using Rust, I thought, but when I started playing out with it, that all changed.</p>
<p>I realized it would take quite some time for me to be productive in Rust, compared to <a href="https://www.typescriptlang.org">TypeScript</a> (TS) or JavaScript. Nothing wrong with that and I would love to do a Rust project because I really like the language, but as I will be building an app on my spare time, which is quite limited nowadays, I want to be productive from the start.</p>
<blockquote>
<p>I never thought I would say this a couple of years ago about a typed language</p>
</blockquote>
<p>With that realization I decided to go with TS for both frontend and backend. And regarding developer satisfaction I must say that, and I never thought I would say this a couple of years ago about a typed language, TS is the programming language I’m most satisfied with so far! The type inference, great intellisense/autocomplete, built-in utility types and union types are real time savers!</p>
<h2 id="why-i-think-types-are-good">Why I think types are good</h2>
<p>When linters became the norm for JavaScript development it was so nice because it could catch common typos like:</p>
<pre><code class="language-typescript"><span class="hljs-keyword">const</span> myFunc = <span class="hljs-function">(<span class="hljs-params">value</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> valeu * <span class="hljs-number">2</span>;
};</code></pre>
<p>And it could do so without any types. But the problem is that it can’t catch similar typos in nested properties:</p>
<pre><code class="language-typescript"><span class="hljs-keyword">const</span> myFunc = <span class="hljs-function">(<span class="hljs-params">obj</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> obj.valeu * <span class="hljs-number">2</span>;
};
<span class="hljs-comment">// or using destructuring</span>
<span class="hljs-keyword">const</span> anotherFunc = <span class="hljs-function">(<span class="hljs-params">{usreId}</span>) =&gt;</span> {
  <span class="hljs-comment">// many lines of code...</span>
  doSomething(usreId); <span class="hljs-comment">// here I even get autocomplete on that wrongly spelled &quot;userId&quot;</span>
};</code></pre>
<p>Such errors will be caught by the TypeScript type checker (in almost real time in your editor) which is so nice, because IMO one of the most common uncaught errors are caused by typos like that especially after a big refactor (if you don’t have almost 100 % test coverage, which I admit I never have). Features like that helps out a lot, even in a one person project!</p>
<h3 id="what-frameworks-to-pick-then">What frameworks to pick then?</h3>
<p>Now that I’ve settled on a programming language it’s time to select the framework(s) to use. What that’ll be you’ll read about in an upcoming post!</p>
]]></description><link>https://joakim.beng.se/blog/posts/choosing-a-web-app-tech-stack-part-1.html</link><guid isPermaLink="false">2ce9ed64-0228-4d95-9ce5-638eaa7db30c</guid><dc:creator><![CDATA[Joakim Carlstein]]></dc:creator><pubDate>Sun, 24 Jan 2021 21:20:00 GMT</pubDate></item><item><title><![CDATA[Building an app I need]]></title><description><![CDATA[<p>I really like new things, like new years, new food and new projects. And here we are, at the beginning of a new year and I’ve been thinking of an app idea I’ve had for a while which I now think it’s the time to realize.</p>
<h2 id="choosing-what-to-build">Choosing what to build</h2>
<p>I have many ideas for potential apps, and the list keeps growing. Don’t we all? And deciding which to build is not an easy task and cause a lot of doubt if the idea even is realizable at all and if it will be usable. During the fall and the holidays I finally picked one idea which I will implement. The idea I’ve settled with is perhaps one of my oldest and I now think that I have accumulated a lot of experience building full stack web based apps from scratch, which is why I think now is the right time to get going with it.</p>
<p>The app idea is not complete and not a new one, there are already plenty of apps in the same area. So why make another one, you might think? Yeah, I’ve asked myself the same question over and over again too. I’ve tested and used so many similar apps that it’s almost tiresome and I’ve found none that satisfies my needs and desires.</p>
<blockquote>
<p>“If you want something done right, do it yourself”</p>
</blockquote>
<p>Of all the apps I’ve found they are either too simple, too complex, too ugly, too slow, too buggy or lacks must have features like sync between devices, cross platform support, offline support, sharing with other users or teams, public sharing or responsive design/mobile plus large screen UI. In other words, the idea for building the app has grown out of pure frustration with the existing alternatives. Although I wouldn&#39;t have picked the idea if I didn&#39;t believe I will make a good app out of it or if it won&#39;t be fun to build.</p>
<h2 id="what-kind-of-app-am-i-talking-about-then">What kind of app am I talking about then?</h2>
<p>The main contender is <a href="https://keep.google.com">Google Keep</a>, which I use daily but am quite frustrated with, but my idea is not limited to its features. Other alternatives that my idea will be able to match feature wise is the now discontinued app Wunderlist (replaced with Microsoft Todo), Todoist, Things 3 and Trello, just to name a few. In the long run it will even compete with bigger “enterprisy” apps like Jira. Off course implementing a competing feature complete alternative to something like Jira isn’t an easy task and will perhaps never happen either. My initial goal is therefore to replace Keep with a less buggy, more reliable and faster alternative. When that goal has been reached I will focus on extending the functionality to be able to replace apps like Trello and similar. I already have great confidence in my planned data model that it will fit for both the initial goal and the next, and even beyond that. I will talk more about the data model in future progress posts.</p>
<h2 id="open-development">Open development</h2>
<p>I will mainly develop this app in my spare time and because I have a family and three kids it will be a long journey, but hopefully a fun one! I&#39;ve been really inspired by <a href="https://twitter.com/vadimdemedes">Vadim Demedes</a> and his work with <a href="https://getlotus.com">Lotus</a> so I will also build this app in the open. If you want to follow along you’ll be able to do it here on the blog (until the app has its own page), on my Twitter (<a href="https://twitter.com/joakimbeng">@joakimbeng</a>) and in an upcoming email newsletter for the app. Please reach out if you have any input, suggestions or just want to give a thumbs up!</p>
]]></description><link>https://joakim.beng.se/blog/posts/building-an-app-i-need.html</link><guid isPermaLink="false">b2d2ca2e-37dc-413d-9aee-f51978451f8c</guid><dc:creator><![CDATA[Joakim Carlstein]]></dc:creator><pubDate>Sat, 16 Jan 2021 09:00:00 GMT</pubDate></item><item><title><![CDATA[A JavaScript test runner in 20 lines]]></title><description><![CDATA[<p>A few weeks ago I saw <a href="https://twitter.com/snuggsi/status/565531862895169536">this tweet about the world&#39;s smallest test library</a> by <a href="https://twitter.com/snuggsi">@snuggsi</a>, which is a great little snippet! Though I see it more as the world&#39;s smallest assertion library, so I&#39;ve decided to do a follow up on my previous post about <a href="/a-javascript-router-in-20-lines/">A JavaScript router in 20 lines</a> and now make a simple test runner in about the same amount of code.</p>
<h2 id="creating-a-test-runner">Creating a test runner</h2>
<h3 id="must-haves">Must haves</h3>
<p>When I think of a test runner there are a few things it must have IMO, mainly:</p>
<ul>
<li>The ability to add multiple tests</li>
<li>Be able to run all tests</li>
<li>Catch unexpected errors, <em>think syntax errors</em></li>
<li>Catch errors thrown by an assertion library</li>
<li>Tell if everything went fine or not, and provide a stack trace if it didn&#39;t</li>
</ul>
<p>Also when writing unit tests in JavaScript I want the test runner to be <em>able to test asynchronous code</em>.</p>
<h3 id="some-code-please">Some code please...</h3>
<p>First we&#39;ll need somewhere to store all tests to run, i.e. the test queue, a simple array will do:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> tests = [];</code></pre>
<p>Then we must have a way to add tests to that queue. I usually use and like <a href="http://mochajs.org/">Mocha</a> with the BDD syntax, which looks like this:</p>
<pre><code class="language-javascript">describe(<span class="hljs-string">&#x27;thing to test&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  it(<span class="hljs-string">&#x27;fulfills something...&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// test code...</span>
  });
});</code></pre>
<p>So let&#39;s make a simplified version of that:</p>
<pre><code class="language-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">test</span> (<span class="hljs-params">name, cb</span>) </span>{
    tests.push({<span class="hljs-attr">name</span>: name, <span class="hljs-attr">test</span>: cb});
}

<span class="hljs-comment">// Usage example:</span>
test(<span class="hljs-string">&#x27;thing to test fulfills something...&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// test code...</span>
});</code></pre>
<p>Simple enough :)</p>
<h4 id="syntax-for-asynchronous-tests">Syntax for asynchronous tests</h4>
<p>How about asynchronous tests then? Once again I&#39;ll take inspiration from the Mocha framework, which uses <code>done</code> callbacks in the tests to execute when your test is done.</p>
<p>With that change our usage example now looks like:</p>
<pre><code class="language-javascript">test(<span class="hljs-string">&#x27;thing to test fulfills something...&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">done</span>) </span>{
  doSomethingAsync(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
    <span class="hljs-comment">// assertions...</span>
    done();
  });
});</code></pre>
<p>Looking good!</p>
<h3 id="running-tests">Running tests</h3>
<p>Let&#39;s add a simple test, which we will run in the next step (<strong>note</strong> I&#39;ll use the small assertion library from the tweet mentioned in the beginning of the post):</p>
<pre><code class="language-javascript">test(<span class="hljs-string">&#x27;1+1 equals 2&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">done</span>) </span>{
  assert(<span class="hljs-number">1</span> + <span class="hljs-number">1</span> === <span class="hljs-number">2</span>, <span class="hljs-string">&#x27;1+1 should be 2&#x27;</span>);
  done();
});</code></pre>
<p>If we want to run just this one test, we could do something like:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> testToRun = tests[<span class="hljs-number">0</span>];
<span class="hljs-keyword">try</span> {
  testToRun.test(done);
} <span class="hljs-keyword">catch</span> (err) {
  done(err);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">done</span> (<span class="hljs-params">err</span>) </span>{
  <span class="hljs-keyword">if</span> (err) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">&#x27;Test failed!&#x27;</span>);
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;Test succeeded!&#x27;</span>);
  }
}</code></pre>
<p>When we run this in <a href="http://nodejs.org">Node</a> or in the browser a nice <code>&quot;Test succeeded!&quot;</code> should show up in the console.</p>
<h4 id="running-all-tests">Running all tests</h4>
<p>Let&#39;s wrap that up in a function and make it get the next test from the queue, each time it&#39;s executed:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> testToRun = tests[i++];
  <span class="hljs-keyword">try</span> {
    testToRun.test(done);
  } <span class="hljs-keyword">catch</span> (err) {
    done(err);
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">done</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">&#x27;Test failed!&#x27;</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;Test succeeded!&#x27;</span>);
    }
  }
}</code></pre>
<p>A little better, but still not useful, we don&#39;t want to manually run the runner once for each test don&#39;t we?</p>
<p>A useful little trick here, inspired by the middleware queue in <a href="http://expressjs.com/">Express</a>, is to wrap the test picking and execution in a function called <code>next</code> which will be passed as the <code>done</code> callback to all tests until there are no tests left. Like this:</p>
<pre><code class="language-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; <span class="hljs-comment">// Move this in here, so it resets on each run...</span>
  next(); <span class="hljs-comment">// Start runner...</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">next</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-keyword">var</span> testToRun = tests[i++];
    <span class="hljs-comment">// Stop test runner on error or when no tests are left:</span>
    <span class="hljs-keyword">if</span> (err || !testToRun) <span class="hljs-keyword">return</span> done(err);
    <span class="hljs-keyword">try</span> {
      testToRun.test(next);
    } <span class="hljs-keyword">catch</span> (err) {
      next(err);
    }
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">done</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">&#x27;Tests failed!&#x27;</span>);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;Tests succeeded!&#x27;</span>);
    }
  }
}</code></pre>
<p>That&#39;s better! Now at least all tests will be run, by calling <code>run()</code> just once.</p>
<h3 id="its-all-about-presentation">It&#39;s all about presentation</h3>
<p>This test runner works, but it does not give you any information of what succeeded and what failed. We need to fix that:</p>
<pre><code class="language-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>;
  <span class="hljs-keyword">var</span> testToRun; <span class="hljs-comment">// Move this here, to get info about last test later...</span>
  next(); <span class="hljs-comment">// Start runner...</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">next</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-keyword">if</span> (testToRun) {
      <span class="hljs-comment">// Show status for last test run:</span>
      <span class="hljs-keyword">if</span> (err) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">&#x27;✘ &#x27;</span> + testToRun.name);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;✔ &#x27;</span> + testToRun.name);
      }
    }
    testToRun = tests[i++];
    <span class="hljs-comment">// Stop test runner on error or when no tests are left:</span>
    <span class="hljs-keyword">if</span> (err || !testToRun) <span class="hljs-keyword">return</span> done(err);
    <span class="hljs-keyword">try</span> {
      <span class="hljs-comment">// Calling `call` makes a better stack trace:</span>
      testToRun.test.call(testToRun.test, next);
    } <span class="hljs-keyword">catch</span> (err) {
      next(err);
    }
  }
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">done</span> (<span class="hljs-params">err</span>) </span>{
      <span class="hljs-comment">// Show all remaining tests as skipped:</span>
    tests.slice(i).map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">skippedTest</span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;-&#x27;</span>, skippedTest.name); });
    <span class="hljs-keyword">if</span> (err) {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">&#x27;\nTests failed!\n&#x27;</span> + err.stack); <span class="hljs-comment">// Add stack trace to output...</span>
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;\nTests succeeded!&#x27;</span>);
    }
  }
}</code></pre>
<p>That&#39;s more like it!</p>
<p>But, there is still one problem. I said <em>20 lines of code</em>, and this is a total of 36 including comments, so there&#39;s still some refactoring that can be done.</p>
<h3 id="wrapping-it-up">Wrapping it up</h3>
<p>Let&#39;s save some lines by removing all comments and refactor some bits and pieces to oneliners, like so:</p>
<pre><code class="language-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>, testToRun;
  (<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">next</span> (<span class="hljs-params">err</span>) </span>{
    <span class="hljs-keyword">if</span> (testToRun) <span class="hljs-built_in">console</span>[err ? <span class="hljs-string">&#x27;error&#x27;</span> : <span class="hljs-string">&#x27;log&#x27;</span>](err ? <span class="hljs-string">&#x27;✘&#x27;</span> : <span class="hljs-string">&#x27;✔&#x27;</span>, testToRun.name);
    <span class="hljs-keyword">if</span> (err || !(testToRun = tests[i++])) <span class="hljs-keyword">return</span> done(err);
    <span class="hljs-keyword">try</span> {
      testToRun.test.call(testToRun.test, next);
    } <span class="hljs-keyword">catch</span> (err) {
      next(err);
    }
  })();
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">done</span> (<span class="hljs-params">err</span>) </span>{
    tests.slice(i).map(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">skippedTest</span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">&#x27;-&#x27;</span>, skippedTest.name); });
    <span class="hljs-built_in">console</span>[err ? <span class="hljs-string">&#x27;error&#x27;</span> : <span class="hljs-string">&#x27;log&#x27;</span>](<span class="hljs-string">&#x27;\nTests &#x27;</span> + (err ? <span class="hljs-string">&#x27;failed!\n&#x27;</span> + err.stack : <span class="hljs-string">&#x27;succeeded!&#x27;</span>));
  }
}</code></pre>
<p>Including the <code>tests</code> array declaration and the <code>test</code> function, for adding tests, it sums up to <strong>20 lines!</strong> How about that :)</p>
<p>Finally <a href="https://gist.github.com/joakimbeng/8f57dae814a4802e2ae6">here&#39;s a gist with the complete version</a> including a basic module wrapper and a runnable usage example.</p>
<p>All the best!</p>
]]></description><link>https://joakim.beng.se/blog/posts/a-javascript-test-runner-in-20-lines.html</link><guid isPermaLink="false">53fe24e3-00ef-4115-b1e9-400019122880</guid><dc:creator><![CDATA[Joakim Carlstein]]></dc:creator><pubDate>Mon, 23 Feb 2015 21:52:08 GMT</pubDate></item><item><title><![CDATA[Slush - replacing Yeoman with Gulp]]></title><description><![CDATA[<p>When I first came across <a href="http://gruntjs.com">Grunt</a> I thought it was a great tool, and it certainly was! Until I started to develop and maintain some grunt plugins of my own. Then I felt that the API was not intuitive enough for a smooth development cycle.
It got even worse when I began maintaining my own huge gruntfile in my <a href="http://yeoman.io">Yeoman</a> MEAN app generator (<a href="http://github.com/klei/generator-klei">generator-klei</a>).</p>
<h2 id="gulp-to-the-rescue">Gulp to the rescue</h2>
<p>Then came <a href="http://gulpjs.com">Gulp</a> and I instantly felt that it was not only a great tool, but even a superb one! I really like the &quot;code before configuration&quot; mantra and even more so the advocacy of DRYness when developing plugins.</p>
<h3 id="easier-to-maintain">Easier to maintain</h3>
<p>The gulp version of my <code>generator-klei</code> is under development (take a look at the <a href="https://github.com/klei/generator-klei/tree/gulp">gulp branch</a> if you&#39;re intrested) and I&#39;ve gone from 600 lines of gruntfile to a 300 lines long gulpfile with maintained functionality!</p>
<h2 id="back-to-the-point">Back to the point</h2>
<p>When developing the Yeoman generator I discovered it wasn&#39;t only the gruntfile that was hard to maintain, but also the generator itself. So a couple of weeks ago I began thinking of how to replace Yeoman with something simpler.</p>
<h3 id="main-features-of-a-generator">Main features of a generator</h3>
<p>First I listed all the features of a Yeoman generator, the features that I&#39;m using anyway:</p>
<ol>
<li>Copying a project structure (with folders and everything)</li>
<li>Prompting the user for some project options</li>
<li>Templating some of the project files depending on the prompt answers</li>
<li>Auto-installing needed dependencies for the generated project</li>
<li>Prompting which files to overwrite (when running the generator a second time)</li>
</ol>
<h3 id="gulp-as-a-generator">Gulp as a generator</h3>
<p>So I thought, wouldn&#39;t this be a great use for gulp?</p>
<p>Let&#39;s see what it handles out of the box:</p>
<ol>
<li>Supported natively by <a href="https://github.com/gulpjs/gulp/blob/master/docs/API.md#gulpsrcglobs-options"><code>gulp.src</code></a></li>
<li>One could use <a href="https://github.com/SBoudrias/Inquirer.js"><code>inquirer</code></a> directly for this</li>
<li>For instance <a href="https://github.com/sindresorhus/gulp-template"><code>gulp-template</code></a> does this</li>
<li>Missing. Could easily be implemented as a gulp plugin <em>(see below)</em></li>
<li>Missing. Could easily be implemented as a gulp plugin <em>(see below)</em></li>
</ol>
<p>As you see, gulp can already act as a simple project generator!</p>
<h4 id="a-basic-gulp-project-scaffolding-example">A basic Gulp project scaffolding example</h4>
<p>Let&#39;s say we have a directory structure for our first simple generator like this:</p>
<pre><code>my-<span class="hljs-keyword">basic-generator/
</span>├── app
│   └── templates           <span class="hljs-comment"># This contains the app template</span>
│       ├── gulpfile.<span class="hljs-keyword">js
</span>│       ├── index.html
│       └── package.<span class="hljs-keyword">json
</span>├── generator-gulpfile.<span class="hljs-keyword">js
</span>└── package.<span class="hljs-keyword">json</span></code></pre>
<p>Then we&#39;ll create a gulpfile made for scaffolding purposes, <code>generator-gulpfile.js</code>:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> gulp = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;gulp&#x27;</span>),
    template = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;gulp-template&#x27;</span>);

gulp.task(<span class="hljs-string">&#x27;default&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> gulp.src(__dirname + <span class="hljs-string">&#x27;/app/templates/**&#x27;</span>) <span class="hljs-comment">// Notice the `__dirname` here</span>
    .pipe(template({})) <span class="hljs-comment">// Empty data for now</span>
    .pipe(gulp.dest(<span class="hljs-string">&#x27;./&#x27;</span>)); <span class="hljs-comment">// Relative to cwd</span>
});</code></pre>
<p>We can then scaffold our project into current working directory like this:</p>
<pre><code class="language-bash">/path/to/my-basic-generator/node_modules/.bin/gulp --gulpfile /path/to/my-basic-generator/generator-gulpfile.js --cwd .</code></pre>
<p>Alright! As you can see, there&#39;s a lot we can do with Gulp already, but it&#39;s not that convenient yet - let&#39;s change that!</p>
<h2 id="introducing-slush---the-streaming-scaffolding-system">Introducing Slush - the streaming scaffolding system</h2>
<p>To make it easier to use a project generator built with Gulp I&#39;ve built <a href="http://slushjs.github.io/generators">Slush</a>. Slush locates all installed Gulp built project generators, from now on called &quot;slush generators&quot;, and makes it possible to run such a generator without the need to specify it&#39;s location, like this:</p>
<pre><code class="language-bash">slush &lt;generator name&gt; [&lt;generator task&gt;]</code></pre>
<p>Slush can, and should be, installed globally with:</p>
<pre><code class="language-bash">npm install -g slush</code></pre>
<h3 id="slush-generators">Slush generators</h3>
<p>Slush itself does not depend on Gulp but each generator must have Gulp as a dependency for this to work, Slush will run the Gulp module local to the generator.</p>
<p>A slush generator should have the <code>&quot;slushgenerator&quot;</code> keyword in its <code>package.json</code> and should be named <code>slush-&lt;generator-name-dashed&gt;</code>, e.g. &quot;slush-angular&quot;.</p>
<p>To make a slush generator locatable for the Slush CLI it must be installed globally, e.g:</p>
<pre><code class="language-bash">npm install -g slush-angular</code></pre>
<h3 id="the-slushfile">The slushfile</h3>
<p>To distinguish between the scaffolding gulpfile and an ordinary gulpfile used for development the former should be named <code>slushfile.js</code>. There&#39;s no difference between an ordinary gulpfile and the slushfile in how you write it, but only how you use it.</p>
<p>All gulp plugins used within a generator&#39;s slushfile must be installed as ordinary project dependencies, i.e. <em>not</em> <code>devDependencies</code>.</p>
<h3 id="making-a-complete-yeoman-like-slush-generator">Making a complete Yeoman like Slush generator</h3>
<p>As you may remember I earlier in the post listed some features of a Yeoman generator that was not currently available natively in gulp or via plugins, which was:</p>
<ul>
<li>Auto-installing needed dependencies for the generated project</li>
<li>Prompting which files to overwrite (when running the generator a second time)</li>
</ul>
<p>So I decided to build two gulp plugins to handle this.</p>
<h4 id="install-project-dependencies-with-gulp-install">Install project dependencies with <a href="https://github.com/slushjs/gulp-install"><code>gulp-install</code></a></h4>
<p>If the file stream contains a <code>package.json</code> file the plugin will trigger a call to <code>npm install</code> in the scaffolded project, and similar if it contains a <code>bower.json</code> file it will run <code>bower install</code>.</p>
<h4 id="prompt-before-overwrite-with-gulp-conflict">Prompt before overwrite with <a href="https://github.com/slushjs/gulp-conflict"><code>gulp-conflict</code></a></h4>
<p>Based on <a href="https://github.com/yeoman/generator/blob/master/lib/util/conflicter.js">Yeoman&#39;s internal conflicter</a> the <code>gulp-conflict</code> plugin will prompt what to do when files in stream is conflicting with files in the given destination directory.</p>
<h3 id="a-complete-slush-generator-example">A complete Slush generator example</h3>
<p>Let&#39;s revisit the basic gulp generator example from above and make it a complete slush generator with prompt, autoinstall and everything.</p>
<p>We still have the same directory structure:</p>
<pre><code>slush-<span class="hljs-keyword">basic/ </span>               <span class="hljs-comment"># By convention</span>
├── app
│   └── templates           <span class="hljs-comment"># This contains the app template</span>
│       ├── gulpfile.<span class="hljs-keyword">js
</span>│       ├── index.html
│       └── package.<span class="hljs-keyword">json
</span>├── slushfile.<span class="hljs-keyword">js </span>           <span class="hljs-comment"># By convention</span>
└── package.<span class="hljs-keyword">json</span></code></pre>
<p>And here&#39;s the content of our <code>slushfile.js</code>:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> gulp = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;gulp&#x27;</span>),
    install = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;gulp-install&#x27;</span>),
    conflict = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;gulp-conflict&#x27;</span>),
    template = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;gulp-template&#x27;</span>),
    inquirer = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;inquirer&#x27;</span>);

gulp.task(<span class="hljs-string">&#x27;default&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">done</span>) </span>{
  inquirer.prompt([
    {<span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;input&#x27;</span>, <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;name&#x27;</span>, <span class="hljs-attr">message</span>: <span class="hljs-string">&#x27;Name for the app?&#x27;</span>}
  ],
  <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">answers</span>) </span>{
    gulp.src(__dirname + <span class="hljs-string">&#x27;/app/templates/**&#x27;</span>) <span class="hljs-comment">// Relative to __dirname</span>
      .pipe(template(answers))
      .pipe(conflict(<span class="hljs-string">&#x27;./&#x27;</span>))
      .pipe(gulp.dest(<span class="hljs-string">&#x27;./&#x27;</span>)) <span class="hljs-comment">// Relative to cwd</span>
      .pipe(install())
      .on(<span class="hljs-string">&#x27;finish&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        done(); <span class="hljs-comment">// Finished!</span>
      });
  });
});</code></pre>
<p><strong>There you have it!</strong> We can then install our new generator with:</p>
<pre><code class="language-bash">npm install -g slush-basic   <span class="hljs-comment"># if it&#x27;s published</span>
<span class="hljs-comment"># or</span>
npm link .                   <span class="hljs-comment"># for development</span></code></pre>
<p>And use it with:</p>
<pre><code class="language-bash">slush basic</code></pre>
<p><strong>Done!</strong> As you can see, with just a few lines of gulp goodness we have recreated the functionality of a Yeoman generator.</p>
<h2 id="final-words">Final words</h2>
<p>This is just the first version of Slush and I&#39;ve probably missed something useful in the whole Yeoman generator workflow, please feel free to comment and contribute!</p>
<h3 id="build-generators">Build generators</h3>
<p>I would like to see as many useful generators out there as possible. I know I&#39;ll be using this instead of Yeoman from now on anyway...</p>
<h3 id="its-gulp">It&#39;s Gulp</h3>
<p>Also remember that Slush comes with no functionality of its own, the only thing it provides is a convention and convenience of running global gulpfiles (in this case slushfiles) with the purpose of scaffolding projects, or anything else useful for that matter. So if something is missing it should probably be implemented as a gulp plugin.</p>
]]></description><link>https://joakim.beng.se/blog/posts/slush-replacing-yeoman-with-gulp.html</link><guid isPermaLink="false">ebf8e11f-e6ba-476d-9213-d84a62ab35b1</guid><dc:creator><![CDATA[Joakim Carlstein]]></dc:creator><pubDate>Mon, 24 Mar 2014 15:27:21 GMT</pubDate></item><item><title><![CDATA[A JavaScript router in 20 lines]]></title><description><![CDATA[<p>Last week I found this post about <a href="http://krasimirtsonev.com/blog/article/Javascript-template-engine-in-just-20-line">writing a template engine in 20 lines</a>, which in turn is inspired by <a href="http://ejohn.org/blog/javascript-micro-templating/">John Resig&#39;s post on the same topic</a>. I find them really simple, interesting and inspiring so I came up with the idea of making a <em>simple client side router in just 20 lines of code</em>.</p>
<h2 id="lets-build-a-router">Let&#39;s build a router</h2>
<p>First we&#39;ll need a html template:</p>
<pre><code class="language-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">&quot;utf-8&quot;</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Building a router<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-comment">// Put John&#x27;s template engine code here...</span>
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></code></pre>
<p>For the templates I&#39;ll use <code>&lt;script&gt;</code> tags with <code>type=&quot;text/html&quot;</code>, which will make the browser not parse the contents of them, like we want it. I place them right after the existing script tag.</p>
<pre><code class="language-html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text/html&quot;</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;home&quot;</span>&gt;</span><span class="handlebars"><span class="xml">
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Router FTW!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
</span></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text/html&quot;</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;template1&quot;</span>&gt;</span><span class="handlebars"><span class="xml">
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Page 1: &lt;%= greeting %&gt;<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>&lt;%= moreText %&gt;<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</span></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;text/html&quot;</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;template2&quot;</span>&gt;</span><span class="handlebars"><span class="xml">
  <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Page 2: &lt;%= heading %&gt;<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</span></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></code></pre>
<p>As you can see they are really basic, that&#39;s because we are focusing on the router part...</p>
<h3 id="hash-urls">Hash URL&#39;s</h3>
<p>For this router I&#39;ll use hash URL&#39;s, i.e. those specified after the <code>#</code> sign in the full URL e.g. <a href="http://example.com/#**/our/url/here">http://example.com/#**/our/url/here</a>**. I could have done it with the <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history">HTML5 History API</a> but I&#39;ll leave that for another time.</p>
<h3 id="handling-route-changes">Handling route changes</h3>
<p>The router will use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window.onhashchange">onhashchange event</a> to handle route changes after page load and the usual <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window.onload">onload event</a> to handle any route in the url on page load.</p>
<h3 id="first-take">First take...</h3>
<p>Let&#39;s begin with making the route registering function:</p>
<pre><code class="language-javascript"><span class="hljs-comment">// A hash to store our routes:</span>
<span class="hljs-keyword">var</span> routes = {};
<span class="hljs-comment">// The route registering function:</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">route</span> (<span class="hljs-params">path, templateId, controller</span>) </span>{
  routes[path] = {<span class="hljs-attr">templateId</span>: templateId, <span class="hljs-attr">controller</span>: controller};
}</code></pre>
<h4 id="registering-routes">Registering routes</h4>
<p>Now we can create new routes yay! <em>Notice that I&#39;m mimicing the controller definition from AngularJS</em>:</p>
<pre><code class="language-javascript">route(<span class="hljs-string">&#x27;/&#x27;</span>, <span class="hljs-string">&#x27;home&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{});
route(<span class="hljs-string">&#x27;/page1&#x27;</span>, <span class="hljs-string">&#x27;template1&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">this</span>.greeting = <span class="hljs-string">&#x27;Hello world!&#x27;</span>;
    <span class="hljs-built_in">this</span>.moreText = <span class="hljs-string">&#x27;Bacon ipsum...&#x27;</span>;
});
route(<span class="hljs-string">&#x27;/page2&#x27;</span>, <span class="hljs-string">&#x27;template2&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">this</span>.heading = <span class="hljs-string">&#x27;I\&#x27;m page two!&#x27;</span>;
});</code></pre>
<p>But yet nothing happens, because we don&#39;t handle the routes yet...</p>
<h4 id="the-actual-route-handler">The actual route handler</h4>
<p>Let&#39;s build the route handler! But first we need somewhere to render our pages, for now I settle with the convention that an element with id <code>view</code> is used as the container to render a page in.</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> el = <span class="hljs-literal">null</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">router</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// Lazy load view element:</span>
    el = el || <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">&#x27;view&#x27;</span>);
    <span class="hljs-comment">// Current route url (getting rid of &#x27;#&#x27; in hash as well):</span>
    <span class="hljs-keyword">var</span> url = location.hash.slice(<span class="hljs-number">1</span>) || <span class="hljs-string">&#x27;/&#x27;</span>;
    <span class="hljs-comment">// Get route by url:</span>
    <span class="hljs-keyword">var</span> route = routes[url];
    <span class="hljs-comment">// Do we have both a view and a route?</span>
    <span class="hljs-keyword">if</span> (el &amp;&amp; route.controller) {
        <span class="hljs-comment">// Render route template with John Resig&#x27;s template engine:</span>
        el.innerHTML = tmpl(route.templateId, <span class="hljs-keyword">new</span> route.controller());
    }
}
<span class="hljs-comment">// Listen on hash change:</span>
<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">&#x27;hashchange&#x27;</span>, router);
<span class="hljs-comment">// Listen on page load:</span>
<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">&#x27;load&#x27;</span>, router);</code></pre>
<p>There we have it! So let&#39;s test it!</p>
<h3 id="testing-the-first-version">Testing the first version</h3>
<p>First we&#39;ll add some navigational links to our layout, to be able to trigger the different routes, and the view element, by putting this inside our body element:</p>
<pre><code class="language-html">  <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&quot;#&quot;</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&quot;#/page1&quot;</span>&gt;</span>Page 1<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">&quot;#/page2&quot;</span>&gt;</span>Page 2<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;view&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>
<p><a href="https://gist.github.com/joakimbeng/7918297/278619bd5ba9b4768eecb0020b09a43f2e8eacea">The complete first version can be found here</a>.</p>
<p>Save and open your complete html file in a modern browser and you should see:</p>
<blockquote>
<p>Router FTW!</p>
</blockquote>
<p>And the navigational links should work as well. You can also try to go to a specific route directly by navigating your browser to e.g. &quot;path/to/your/router.html#/page1&quot; and you should see the contents of our &quot;page1&quot;.</p>
<h3 id="bonus---one-directional-data-binding">Bonus - one-directional data-binding!</h3>
<p>To make the router a little more useful I&#39;m going to add one-directional data-binding for automatic updating of the view when data in the controllers change. For that I&#39;ll be using <a href="https://simpl.info/observe/"><code>Object.observe()</code></a> <em>(note: I didn&#39;t need Chrome Canary for the flag to exist, I could enable it in Chrome 32-beta as well)</em></p>
<p>I will extend the router handling function to register an object observer which rerenders the current view, so no advanced partial view updates at this time.</p>
<h4 id="router-with-object-observation">Router with object observation</h4>
<p>With a small rewrite the new router look like this:</p>
<pre><code class="language-javascript"><span class="hljs-keyword">var</span> el = <span class="hljs-literal">null</span>, current = <span class="hljs-literal">null</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">router</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Lazy load view element:</span>
  el = el || <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">&#x27;view&#x27;</span>);
  <span class="hljs-comment">// Clear existing observer:</span>
  <span class="hljs-keyword">if</span> (current) {
    <span class="hljs-built_in">Object</span>.unobserve(current.controller, current.render);
    current = <span class="hljs-literal">null</span>;
  }
  <span class="hljs-comment">// Current route url (getting rid of &#x27;#&#x27; in hash as well):</span>
  <span class="hljs-keyword">var</span> url = location.hash.slice(<span class="hljs-number">1</span>) || <span class="hljs-string">&#x27;/&#x27;</span>;
  <span class="hljs-comment">// Get route by url:</span>
  <span class="hljs-keyword">var</span> route = routes[url];
  <span class="hljs-comment">// Do we have both a view and a route?</span>
  <span class="hljs-keyword">if</span> (el &amp;&amp; route.controller) {
    <span class="hljs-comment">// Set current route information:</span>
    current = {
      <span class="hljs-attr">controller</span>: <span class="hljs-keyword">new</span> route.controller,
      <span class="hljs-attr">template</span>: tmpl(route.templateId),
      <span class="hljs-attr">render</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-comment">// Render route template with John Resig&#x27;s template engine:</span>
        el.innerHTML = <span class="hljs-built_in">this</span>.template(<span class="hljs-built_in">this</span>.controller);
      }
    };
    <span class="hljs-comment">// Render directly:</span>
    current.render();
    <span class="hljs-comment">// And observe for changes to trigger rerender:</span>
    <span class="hljs-built_in">Object</span>.observe(current.controller, current.render.bind(current));
  }
}</code></pre>
<p><strong>That&#39;s it!</strong> As you can see, there&#39;s not that much extra code to get one-directional data-binding to work. I think the <code>Object.observe()</code> function is really great and can come in handy in many different scenarios in the future.</p>
<h4 id="testing-the-data-binding">Testing the data-binding</h4>
<p>To test the data-binding we&#39;ll just update one of the routes with a <code>setTimeout</code> to emulate a long running asynchronous function:</p>
<pre><code class="language-javascript">route(<span class="hljs-string">&#x27;/page1&#x27;</span>, <span class="hljs-string">&#x27;template1&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">this</span>.greeting = <span class="hljs-string">&#x27;Hello world!&#x27;</span>;
  <span class="hljs-built_in">this</span>.moreText = <span class="hljs-string">&#x27;Loading...&#x27;</span>;
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">this</span>.moreText = <span class="hljs-string">&#x27;Bacon ipsum...&#x27;</span>;
  }.bind(<span class="hljs-built_in">this</span>), <span class="hljs-number">500</span>);
});</code></pre>
<p>Then when you go to the route <code>#/page1</code> you should se &quot;Loading...&quot; for a short while which is then exchanged with &quot;Bacon ipsum...&quot;.</p>
<h3 id="result">Result</h3>
<p><a href="https://gist.github.com/joakimbeng/7918297">The full version with data-binding can be found here</a>. I admit that it isn&#39;t only 20 lines of code, it&#39;s 28 without the comments, so it wasn&#39;t that far off :)</p>
<p>Even with data-binding this is still a really basic router though, for example parameter support is still missing, but this was made more as an experiment than a complete library anyway.</p>
<p>Hopefully someone liked it, as I did when coding it ;)</p>
]]></description><link>https://joakim.beng.se/blog/posts/a-javascript-router-in-20-lines.html</link><guid isPermaLink="false">0092e4c1-6ea1-478a-8cc6-9afecab35ba8</guid><dc:creator><![CDATA[Joakim Carlstein]]></dc:creator><pubDate>Sun, 15 Dec 2013 19:46:03 GMT</pubDate></item><item><title><![CDATA[It&#39;s here, my Ghost blog]]></title><description><![CDATA[<p><strong>For quite awhile now I&#39;ve been thinking</strong> about creating a blog where I could share my thoughts about anything, and particularly coding &amp; development...</p>
<p>As I&#39;m really into <em>javascript</em> nowadays I was very glad to see the <a href="http://blog.ghost.org/public-launch/">public launch of Ghost</a> which is the blog platform that this one is built with.</p>
<p>And here&#39;s how I got it up and running:</p>
<h2 id="ghost--appfog">Ghost + Appfog</h2>
<p>I decided that I wanted to host my blog on <a href="http://appfog.com">Appfog</a> because I think it&#39;s a good and easy to use service, moreover I&#39;ve discovered that they have a great uptime using another useful service <a href="http://pingdom.com">Pingdom</a>.</p>
<h3 id="making-ghost-work-on-appfog">Making Ghost work on Appfog</h3>
<h4 id="ignore-nodejs-010-requirement">Ignore NodeJS 0.10 requirement</h4>
<p>Currently Appfog doesn&#39;t support NodeJS 0.10 which Ghost claims it needs, but fear not! Just comment out these lines in <code>./core/server.js</code> (starting at line 382):</p>
<pre><code>    <span class="hljs-keyword">if</span> (!semver.satisfies(process.versions.node, packageInfo.engines.node)) {
        console.log(
            <span class="hljs-string">&quot;\nERROR: Unsupported version of Node&quot;</span>.red,
            <span class="hljs-string">&quot;\nGhost needs Node version&quot;</span>.red,
            packageInfo.engines.node.yellow,
            <span class="hljs-string">&quot;you are using version&quot;</span>.red,
            process.versions.node.yellow,
            <span class="hljs-string">&quot;\nPlease go to http://nodejs.org to get the latest version&quot;</span>.green
        );

        process.<span class="hljs-keyword">exit</span>(<span class="hljs-number">0</span>);
    }</code></pre>
<p>And remove line 9-11 in <code>./package.json</code>:</p>
<pre><code>{
  <span class="hljs-comment">// these lines:</span>
  <span class="hljs-attr">&quot;engines&quot;</span>: {
    <span class="hljs-attr">&quot;node&quot;</span>: <span class="hljs-string">&quot;&gt;=0.10.* &lt;0.11.4&quot;</span>
  },
  <span class="hljs-comment">// ...</span>
}</code></pre>
<p><strong>N.B</strong> Probably Ghost has a good reason for the 0.10 requirement, but I haven&#39;t found anything that doesn&#39;t work yet. <em>Please let me know me if you do!</em></p>
<h4 id="change-db-to-mysql">Change DB to MySQL</h4>
<p>Ghost uses Sqlite by default but have support for MySQL as well, which Appfog does too. I followed <a href="http://www.codeforest.net/ghost-blogging-platform-review">this post at Codeforest</a> and adapted it to Appfog like this:</p>
<p>Add a MySQL service to your Appfog application, then modify <code>./config.js</code> lines 4-5 to this:</p>
<pre><code><span class="hljs-keyword">var</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">&#x27;path&#x27;</span>),
    mysql = process.env.NODE_ENV === <span class="hljs-string">&#x27;production&#x27;</span> ? <span class="hljs-built_in">JSON</span>.parse(process.env.VCAP_SERVICES)[<span class="hljs-string">&quot;mysql-5.1&quot;</span>][<span class="hljs-number">0</span>].credentials : {},
    config;</code></pre>
<p>And then under the <code>production</code> config section set the database configuration to the following:</p>
<pre><code><span class="hljs-keyword">database</span>: {
    client: <span class="hljs-string">&#x27;mysql&#x27;</span>,
    <span class="hljs-keyword">connection</span>: {
        <span class="hljs-keyword">database</span>: mysql.name,
        host: mysql.host,
        <span class="hljs-keyword">user</span>: mysql.<span class="hljs-keyword">user</span>,
        <span class="hljs-keyword">password</span>: mysql.<span class="hljs-keyword">password</span>
    },
    <span class="hljs-keyword">debug</span>: <span class="hljs-keyword">false</span>
},</code></pre>
<p>Also don&#39;t forget to install <code>mysql</code> module with:</p>
<pre><code>npm <span class="hljs-keyword">install</span> mysql</code></pre>
<h3 id="profit">Profit</h3>
<p>That&#39;s it, now you can run:</p>
<pre><code>af <span class="hljs-keyword">update</span> <span class="hljs-symbol">&lt;your_app_name&gt;</span></code></pre>
<p>And it should work!</p>
<p><strong>Happy blogging!</strong></p>
]]></description><link>https://joakim.beng.se/blog/posts/its-here-my-ghost-blog.html</link><guid isPermaLink="false">37bfc3ca-11fb-47f7-9bbe-0fc4b27e9837</guid><dc:creator><![CDATA[Joakim Carlstein]]></dc:creator><pubDate>Tue, 03 Dec 2013 18:32:37 GMT</pubDate></item></channel></rss>