<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>Duncan Britt's Blog</title>
<atom:link href="http://duncanbritt.com/feed.xml" rel="self" type="application/rss+xml" />
<link>http://duncanbritt.com</link>
<description><![CDATA[Latest blog posts]]></description>
<language>en</language>
<lastBuildDate>Sun, 19 Jul 2026 11:37:18 -0600</lastBuildDate>
<generator>build-site.el</generator>
<item>
<title>srs.el - My spaced repetition system for emacs</title>
<link>http://duncanbritt.com/blog/srs/srs.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/srs/srs.html</guid>
<pubDate>Sat, 27 Jun 2026 00:00:00 -0600</pubDate>
<description><![CDATA[<ul class="org-ul">
<li><a href="https://melpa.org/#/srs" target="_blank">
  <img style="max-width: 137px;" src="https://melpa.org/packages/srs-badge.svg" alt="srs-badge.svg" class="org-svg">
</a></li>
<li><a href="https://github.com/Duncan-Britt/srs.el" target="_blank">Repo</a></li>
</ul>

<p>
My previous attempts to get into <a href="https://en.wikipedia.org/wiki/Spaced_repetition">spaced repetition</a> had always been inhibited by the inconvenience of it, so, inspired by <a href="https://borretti.me/article/hashcards-plain-text-spaced-repetition">hashcards</a>, I decided to make my own spaced repetition system (SRS), with the goal of being as friction-less as possible. And to me that means at minimum it must be integrated into my favorite text editor!
</p>

<video controls width="100%">
  <source src="https://github.com/Duncan-Britt/srs.el/raw/media/media/20260627T143545--srs-package-demo.mp4" type="video/mp4">
  Your browser does not support video playback.
</video>
<br />
<br />

<p>
Some things I like about it:
</p>
<ul class="org-ul">
<li>No restrictions on where flash cards can be placed, allowing me to embed them in my notes</li>
<li>Minimal syntax</li>
<li>All metadata is stored locally as plain text</li>
<li>When reviewing my flashcards, I can freely type my answers</li>
</ul>

<details>
<summary>Installation</summary>
<p>
To try it out, add something like this to your Emacs configuration:
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span class="org-keyword">use-package</span> srs
  <span class="org-builtin">:ensure</span> t
  <span class="org-builtin">:config</span>
  (add-to-list 'srs-path-list (expand-file-name <span class="org-string">"~/notes/*.org"</span>))
  (srs-set-prefix-kbd <span class="org-string">"s-"</span>))
</pre>
</div>

</details>
]]></description>
</item>
<item>
<title>Tags, Not Taxonomies</title>
<link>http://duncanbritt.com/blog/tags-not-taxonomies/tags-not-taxonomies.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/tags-not-taxonomies/tags-not-taxonomies.html</guid>
<pubDate>Mon, 08 Sep 2025 00:00:00 -0600</pubDate>
<description><![CDATA[<p>
As someone who loves collecting notes, ideas, bookmarks, etc, and someone heavily reliant on to-do lists, the revelation that I can organize everything on my computer using tags has been a game changer. When it comes to organizing anything on a computer, I think you should almost always favor tags over categorization.
</p>

<ol class="org-ol">
<li>A hierarchy of categories—such as folders and sub-folders, or headings and subheadings within a document—only affords one way to find things, but tags allow you to query for information in a variety of different ways. A single photo in your photo album may be at the intersection of a variety of different topics of interest for you—travel, nature, a calendar year, a certain loved-one. And any of those topics should allow you to query and retrieve the photo, along with whatever else might also be relevant at the time.</li>

<li>Forcing your files/media/text into a preconceived taxonomy creates a lot of friction whenever something doesn't neatly fit. You end up re-categorizing, which, apart from being time consuming, doesn't address the root cause—there is a many-to-many relationship between information and the topics by which you may one day wish to query it.</li>
</ol>


<div id="org8ba6887" class="figure">
<p><img src="http://duncanbritt.com/blog/tags-not-taxonomies/.images/costa-rica.jpg" alt="costa-rica.jpg" width="400px" />
</p>
</div>
<div id="outline-container-org086f5cb" class="outline-2">
<h2 id="org086f5cb">File Management</h2>
<div class="outline-text-2" id="text-org086f5cb">
<p>
Files can be tagged in a robust and portable way by using a naming convention which embeds tags in the file names. I use these tags to filter long lists of files down to the intersection of some topics.
</p>
<video width="100%" src="http://duncanbritt.com/blog/tags-not-taxonomies/file-tags.mp4" controls playsinline></video>
<p>
This is how I organize my notes, links, and even my Emacs configuration. Manually naming all files in this manner would be tedious, but software can expedite the process. In my case, I use the <a href="https://protesilaos.com/emacs/denote">Denote</a> Emacs package, which is where I got the idea.
</p>

<details>
<summary>Filtering directories in Emacs</summary>
<p>
To filter the directories, I use the <code>dired-narrow</code> emacs package.
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span class="org-keyword">use-package</span> dired-narrow
  <span class="org-builtin">:ensure</span> t
  <span class="org-builtin">:bind</span> ((<span class="org-builtin">:map</span> dired-mode-map
               (<span class="org-string">"C-s"</span> . dired-narrow))))
</pre>
</div>

</details>
</div>
</div>
<div id="outline-container-org1615e80" class="outline-2">
<h2 id="org1615e80">Project Management</h2>
<div class="outline-text-2" id="text-org1615e80">
<p>
I use org-mode in Emacs for project management. Most of my <b>to-do</b> items are fairly concrete, but some are high-level goals. Often times these high-level goals have some overlapping sub-tasks, so nesting tasks would be a poor-fit. Thankfully, org-mode supports tagging <b>to-do</b> items, and querying by tags. And I think it's quite nice if those high-level <b>to-do</b>'s act as links to all the associated sub-tasks, so I built a command to create those links.
</p>

<video width="100%" src="http://duncanbritt.com/blog/tags-not-taxonomies/org-tags-link.mp4" controls playsinline></video>
<label><i>Following the <b>Create Mobile App</b> link filters out all tasks without the 'mobile' tag.</i></label>

<details>
<summary>Details</summary>
<p>
You can filter org headings by tags using the <code>org-sparse-tree</code> command.
</p>

<div class="org-src-container">
<label class="org-src-name"><span class="listing-number">Listing 1: </span>My command for creating links to tags.</label><pre class="src src-emacs-lisp">(<span class="org-keyword">defun</span> <span class="org-function-name">my/org-tags-link</span> (tags-string link-text todo-only)
  <span class="org-doc">"Insert org-mode link text in buffer at point matching tags</span>
<span class="org-doc">defined in TAGS-STRING. Link, when visited, will produce a sparse</span>
<span class="org-doc">tree of org headings matching TAGS-STRING.</span>

<span class="org-doc">When called interactively, prompt the user for tags."</span>
  (<span class="org-keyword">interactive</span>
   (<span class="org-keyword">let*</span> ((buffer-tags (mapcan #'identity (org-get-buffer-tags)))
          (tags-list-included
           (completing-read-multiple <span class="org-string">"With tag(s): "</span> buffer-tags nil t nil))
          (tags-list-excluded
           (completing-read-multiple <span class="org-string">"Excluding tag(s): "</span> buffer-tags nil t nil)))
     (list
      <span class="org-comment-delimiter">;; </span><span class="org-comment">tags-string</span>
      (concat (apply #'concat
                     (mapcar (<span class="org-keyword">lambda</span> (tag)
                               (concat <span class="org-string">"+"</span> tag))
                             tags-list-included))
              (apply #'concat
                     (mapcar (<span class="org-keyword">lambda</span> (tag)
                               (concat <span class="org-string">"-"</span> tag))
                             tags-list-excluded)))
      <span class="org-comment-delimiter">;; </span><span class="org-comment">link-text</span>
      (read-string <span class="org-string">"Description: "</span>)
      <span class="org-comment-delimiter">;; </span><span class="org-comment">todo only?</span>
      (intern (completing-read <span class="org-string">"Todo only? "</span> '(t nil))))))
  (insert (format <span class="org-string">"[[elisp:(org-match-sparse-tree %s \"%s\")][%s]]"</span> todo-only tags-string link-text)))
</pre>
</div>

</details>
</div>
</div>
<div id="outline-container-orgcc7b105" class="outline-2">
<h2 id="orgcc7b105">Link Management</h2>
<div class="outline-text-2" id="text-orgcc7b105">
<p>
When I find something cool on the web that I want to save for a rainy day, I don't like to use my browser's bookmark system because
a) there's no support for tags and
b) I don't want my collection of links to be tied to a particular browser or computer.
And most times, when I'm searching the information I have stored, I care little whether a file happens to be on my computer or someone else's. So I figured, why not treat my collected web-links as first-class citizens among the rest of my note files? In practice, this means I have a file for each link I want to save, and I configured my file browser in Emacs to treat files with the <i>weblink</i> tag in a special way—opening the embedded URL in my browser when I would otherwise be visiting the file. When I want to save a new link to my notes, I have a keybinding which writes a file to my notes directory based on the URL in my clipboard.
</p>

<details>
<summary>Details</summary>
<p>
To replicate my link management workflow you can install <a href="https://github.com/Duncan-Britt/denote-dired-weblinks">my package</a> for it.
</p>

<div class="org-src-container">
<label class="org-src-name"><span class="listing-number">Listing 2: </span>Example use-package declaration compatible with the Elpaca package manager.</label><pre class="src src-emacs-lisp">(<span class="org-keyword">use-package</span> denote-dired-weblinks
 <span class="org-builtin">:ensure</span> (<span class="org-builtin">:host</span> github <span class="org-builtin">:repo</span> <span class="org-string">"Duncan-Britt/denote-dired-weblinks"</span>) 
 <span class="org-builtin">:hook</span> (dired-mode . denote-dired-weblinks-mode)
 <span class="org-builtin">:bind</span> ((<span class="org-string">"s-b"</span> . denote-dired-weblinks-create-bookmark)))
</pre>
</div>
</details>
</div>
</div>
]]></description>
</item>
<item>
<title>A New Way to Edit Jupyter Python Notebooks in Emacs</title>
<link>http://duncanbritt.com/blog/jupyter-ascending/jupyter-ascending.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/jupyter-ascending/jupyter-ascending.html</guid>
<pubDate>Mon, 05 May 2025 00:00:00 -0600</pubDate>
<description><![CDATA[<ul class="org-ul">
<li><a href="https://melpa.org/#/jupyter-ascending" target="_blank">
  <img style="max-width: 137px;" src="https://melpa.org/packages/jupyter-ascending-badge.svg" alt="srs-badge.svg" class="org-svg">
</a></li>
<li><a href="https://github.com/Duncan-Britt/jupyter-ascending" target="_blank">Repo</a></li>
</ul>

<p>
I created the Jupyter Ascending package to facilitate editing and executing code in a Jupyter Python notebook from Emacs. It provides commands which utilize the <a href="https://jupytext.readthedocs.io/en/latest/">Jupytext</a> and <a href="https://github.com/imbue-ai/jupyter_ascending">Jupyter Ascending</a> command line tools to
</p>
<ul class="org-ul">
<li>render .ipynb notebooks as Python source files,</li>
<li>synchronize the state of the 2 files, and</li>
<li>execute code in the Jupyter notebook.</li>
</ul>
<div id="outline-container-org4e96cc5" class="outline-2">
<h2 id="org4e96cc5">Demo</h2>
<div class="outline-text-2" id="text-org4e96cc5">

<div id="orgda8d4c1" class="figure">
<p><img src="https://raw.githubusercontent.com/Duncan-Britt/jupyter-ascending/refs/heads/demo/demo/jup-basic.gif" alt="jup-basic.gif" />
</p>
<p><span class="figure-number">Figure 1: </span>Python usage</p>
</div>


<div id="org1c34592" class="figure">
<p><img src="https://raw.githubusercontent.com/Duncan-Britt/jupyter-ascending/refs/heads/demo/demo/jup-markdown.gif" alt="jup-markdown.gif" />
</p>
<p><span class="figure-number">Figure 2: </span>Markdown usage</p>
</div>


<div id="orge9663b1" class="figure">
<p><img src="https://raw.githubusercontent.com/Duncan-Britt/jupyter-ascending/refs/heads/demo/demo/jup-setup.gif" alt="jup-setup.gif" />
</p>
<p><span class="figure-number">Figure 3: </span>Starting up a session</p>
</div>
</div>
</div>
<div id="outline-container-orgdb4a33b" class="outline-2">
<h2 id="orgdb4a33b">Features</h2>
<div class="outline-text-2" id="text-orgdb4a33b">
<ul class="org-ul">
<li>Synchronization: Editing and saving the Python buffer automatically updates the Jupyter notebook</li>
<li>Cell execution commands: Run individual cells or the entire notebook</li>
<li>Navigation tools: Jump between cells with simple commands</li>
<li>Cell management: Create new cells and toggle between code and markdown types</li>
<li>Enhanced markdown editing:
<ul class="org-ul">
<li>Edit markdown cells in dedicated markdown buffers (similar to Org mode's special edit mode)</li>
<li>Automatic comment insertion when pressing return in markdown cells</li>
</ul></li>
<li>Setup utilities: Commands for starting Jupyter notebooks and creating synchronized file pairs</li>
</ul>
</div>
</div>
<div id="outline-container-org75e9595" class="outline-2">
<h2 id="org75e9595">Installation</h2>
<div class="outline-text-2" id="text-org75e9595">
<p>
Jupyter Ascending is available on <a href="https://melpa.org/#/jupyter-ascending">MELPA</a>.
</p>
</div>
<div id="outline-container-org8914e3b" class="outline-3">
<h3 id="org8914e3b">Prerequisites</h3>
<div class="outline-text-3" id="text-org8914e3b">
<p>
The following dependencies must be installed first.
</p>

<p>
If you haven't already installed <a href="https://jupyter.org/install">Jupyter</a>:
</p>
<div class="org-src-container">
<pre class="src src-sh">pip install notebook
</pre>
</div>

<p>
Then install the <a href="https://github.com/imbue-ai/jupyter_ascending">Jupyter Ascending</a> command line tool.
</p>
<div class="org-src-container">
<pre class="src src-sh">pip install jupyter_ascending &amp;&amp;
python3 -m jupyter nbextension    install jupyter_ascending --sys-prefix --py &amp;&amp; <span class="org-sh-escaped-newline">\</span>
python3 -m jupyter nbextension     enable jupyter_ascending --sys-prefix --py &amp;&amp; <span class="org-sh-escaped-newline">\</span>
python3 -m jupyter serverextension enable jupyter_ascending --sys-prefix --py
</pre>
</div>

<p>
Installing <a href="https://github.com/imbue-ai/jupyter_ascending">Jupyter Ascending</a> (the command line tool) should install <a href="https://jupytext.readthedocs.io/en/latest/">jupytext</a>, but if not, run <code>pip install jupytext</code>.
</p>
</div>
</div>
<div id="outline-container-orgdf8fe9c" class="outline-3">
<h3 id="orgdf8fe9c">Configuration</h3>
<div class="outline-text-3" id="text-orgdf8fe9c">
<p>
Here's a sample installation which
</p>
<ul class="org-ul">
<li>provides keybindings for common commands in <code>jupyter-ascending-mode</code> and</li>
<li>uses the minor mode when opening python files with the <code>.sync</code> suffix just before the file extension.</li>
</ul>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span class="org-keyword">use-package</span> jupyter-ascending
  <span class="org-builtin">:ensure</span> t
  <span class="org-builtin">:hook</span> (python-mode . (<span class="org-keyword">lambda</span> ()
                         (<span class="org-keyword">when</span> (<span class="org-keyword">and</span> buffer-file-name
                                    (string-match-p <span class="org-string">"\\.sync\\.py\\'"</span> buffer-file-name))
                           (jupyter-ascending-mode 1))))
  <span class="org-builtin">:bind</span> (<span class="org-builtin">:map</span> jupyter-ascending-mode-map
              (<span class="org-string">"C-c C-k"</span> . jupyter-ascending-execute-line)
              (<span class="org-string">"C-c C-a"</span> . jupyter-ascending-execute-all)
              (<span class="org-string">"C-c C-n"</span> . jupyter-ascending-next-cell)
              (<span class="org-string">"C-c C-p"</span> . jupyter-ascending-previous-cell)
              (<span class="org-string">"C-c t"</span> . jupyter-ascending-cycle-cell-type)
              (<span class="org-string">"C-c '"</span> . jupyter-ascending-edit-markdown-cell)))
</pre>
</div>
</div>
</div>
</div>
<div id="outline-container-org3d3e9d9" class="outline-2">
<h2 id="org3d3e9d9">Usage</h2>
<div class="outline-text-2" id="text-org3d3e9d9">
<p>
<b>Create a notebook pair</b> with
    <code>M-x jupyter-ascending-create-notebook-pair RET example RET</code>
Or, equivalently
    <code>python3 -m jupyter_ascending.scripts.make_pair --base example</code>
This creates synced files: <code>example.sync.py</code> and <code>example.sync.ipynb</code>
</p>

<p>
<b>If you have an existing Jupyter notebook, create a python file from it:</b>
    <code>M-x jupyter-ascending-convert-notebook RET example.ipynb RET</code>
Or, equivalently,
    <code>jupytext --to py:percent &lt;file_name&gt;</code>
and then add the <code>.sync</code> suffix to both files
</p>

<p>
<b>Start Jupyter and open the notebook:</b>
With <code>example.sync.py</code> open,
    <code>M-x jupyter-ascending-start-notebook</code>
Or, equivalently,
    <code>python3 -m jupyter notebook example.sync.ipynb</code>
</p>


<p>
Within your Python file, a line starting with <code># %%</code> deliminates a new cell.
</p>
<div class="org-src-container">
<pre class="src src-python"><span class="org-comment-delimiter"># </span><span class="org-comment">%% [markdown]</span>
<span class="org-comment-delimiter"># </span><span class="org-comment">This is a markdown cell.</span>
<span class="org-comment-delimiter"># </span><span class="org-comment">Below is a code cell.</span>

<span class="org-comment-delimiter"># </span><span class="org-comment">%%</span>
<span class="org-keyword">def</span> <span class="org-function-name">g</span>(x):
  <span class="org-keyword">return</span> 3<span class="org-operator">*</span>x
</pre>
</div>

<p>
When you edit and save the Python source file, you should see the Jupyter notebook running in your browser update straight away.
</p>

<p>
I recommend you create keybindings for all the following commands:
</p>
<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">


<colgroup>
<col  class="org-left" />

<col  class="org-left" />
</colgroup>
<thead>
<tr>
<th scope="col" class="org-left">Command</th>
<th scope="col" class="org-left">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="org-left"><code>jupyter-ascending-execute-line</code></td>
<td class="org-left">Execute cell at cursor</td>
</tr>

<tr>
<td class="org-left"><code>jupyter-ascending-execute-all</code></td>
<td class="org-left">Execute all cells</td>
</tr>

<tr>
<td class="org-left"><code>jupyter-ascending-next-cell</code></td>
<td class="org-left">Move to next cell or create new cell</td>
</tr>

<tr>
<td class="org-left"><code>jupyter-ascending-previous-cell</code></td>
<td class="org-left">Move to previous cell</td>
</tr>

<tr>
<td class="org-left"><code>jupyter-ascending-edit-markdown-cell</code></td>
<td class="org-left">Edit Markdown cell in dedicated buffer</td>
</tr>

<tr>
<td class="org-left"><code>jupyter-ascending-cycle-cell-type</code></td>
<td class="org-left">Toggle between Markdown and code cells</td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="outline-container-org15ae315" class="outline-2">
<h2 id="org15ae315">Limitations</h2>
<div class="outline-text-2" id="text-org15ae315">
<p>
This package only works with Python notebooks because the <a href="https://github.com/imbue-ai/jupyter_ascending">Jupyter Ascending</a> command line tool only supports Python notebooks.  See here: <a href="https://github.com/imbue-ai/jupyter_ascending/issues/25">https://github.com/imbue-ai/jupyter_ascending/issues/25</a>
</p>
</div>
</div>
<div id="outline-container-org2ed2c96" class="outline-2">
<h2 id="org2ed2c96">Alternatives</h2>
<div class="outline-text-2" id="text-org2ed2c96">
<p>
I think <a href="https://martibosch.github.io/jupyter-emacs-universe/">this blog post</a> from 2023 gives a good overview of the other options for editing Jupyter Notebooks from Emacs. It covers <a href="https://github.com/emacs-jupyter/jupyter/tree/3615c2de16988c4dd9d1978bfa10ee3092e85b33?tab=readme-ov-file#related-packages">emacs-jupyter</a> and <a href="https://github.com/millejoh/emacs-ipython-notebook">ein</a>.
</p>
</div>
</div>
<div id="outline-container-orgd1d9c9e" class="outline-2">
<h2 id="orgd1d9c9e">Motivation</h2>
<div class="outline-text-2" id="text-orgd1d9c9e">
<p>
I created this package because many of my Computer Science courses force me to use Jupyter notebooks. Of course, I would rather use <a href="https://orgmode.org/">Org mode</a>, but that's life. And I've since come to appreciate the ability to have auto-completions while editing notebooks, or just treat the notebook as a normal Python file and execute it without Jupyter. I was aware of the other Emacs packages for working with Jupyter, which have the benefit of not being limited to just Python. But this package suits my personal taste very well, so I'm a happy user.
</p>
</div>
</div>
]]></description>
</item>
<item>
<title>A Better Meta Key for Emacs</title>
<link>http://duncanbritt.com/blog/ergo-meta/ergo-meta.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/ergo-meta/ergo-meta.html</guid>
<pubDate>Sat, 26 Apr 2025 00:00:00 -0600</pubDate>
<description><![CDATA[<p><a href="http://duncanbritt.com/blog/ergo-meta/ergo-meta.html">Read more</a></p>]]></description>
</item>
<item>
<title>Decluttering my Org Agenda and File System</title>
<link>http://duncanbritt.com/blog/decluttering/decluttering.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/decluttering/decluttering.html</guid>
<pubDate>Thu, 19 Sep 2024 00:00:00 -0600</pubDate>
<description><![CDATA[<div id="outline-container-orga758672" class="outline-2">
<h2 id="orga758672">Decluttering my files</h2>
<div class="outline-text-2" id="text-orga758672">
<p>
Like the home, the home directory, without vigilance, tends toward chaos. I had accumulated files and folders that I no longer used, but I hesitated to delete anything because it's irreversible. So I created a shell script which allows me to move files into an <code>~/archive</code> directory where the file path mirrors that of the location from whence it came.
</p>

<details>
  <summary>Shell script</summary>

<p>
Archiving sibling files and folders won't create duplicates or clobber existing directories in the archive.
</p>
<div class="org-src-container">
<pre class="src src-sh"><span class="org-comment-delimiter">#</span><span class="org-comment">!/bin/</span><span class="org-keyword">bash</span>

<span class="org-comment-delimiter"># </span><span class="org-comment">Archive directory</span>
<span class="org-variable-name">ARCHIVE_DIR</span>=<span class="org-string">"$HOME/archive"</span>

<span class="org-comment-delimiter"># </span><span class="org-comment">Check if a file or directory is specified</span>
<span class="org-keyword">if</span> [ -z <span class="org-string">"$1"</span> ]; <span class="org-keyword">then</span>
  <span class="org-builtin">echo</span> <span class="org-string">"Usage: archive &lt;file-or-directory&gt;"</span>
  <span class="org-keyword">exit</span> 1
<span class="org-keyword">fi</span>

<span class="org-comment-delimiter"># </span><span class="org-comment">File or directory to archive</span>
<span class="org-variable-name">TARGET</span>=<span class="org-string">"$1"</span>

<span class="org-comment-delimiter"># </span><span class="org-comment">Get the current directory relative to home</span>
<span class="org-keyword">if</span> [ <span class="org-string">"$(pwd)"</span> == <span class="org-string">"$HOME"</span> ]; <span class="org-keyword">then</span>
  <span class="org-variable-name">CURRENT_DIR</span>=<span class="org-string">""</span>
<span class="org-keyword">else</span>
  <span class="org-variable-name">CURRENT_DIR</span>=$(<span class="org-builtin">pwd</span> | sed <span class="org-string">"s|^$HOME/||"</span>)
<span class="org-keyword">fi</span>

<span class="org-comment-delimiter"># </span><span class="org-comment">Construct the full path of the target</span>
<span class="org-keyword">if</span> [ -z <span class="org-string">"$CURRENT_DIR"</span> ]; <span class="org-keyword">then</span>
  <span class="org-variable-name">RELATIVE_TARGET_PATH</span>=<span class="org-string">"$TARGET"</span>
<span class="org-keyword">else</span>
  <span class="org-variable-name">RELATIVE_TARGET_PATH</span>=<span class="org-string">"$CURRENT_DIR/$TARGET"</span>
<span class="org-keyword">fi</span>

<span class="org-comment-delimiter"># </span><span class="org-comment">Construct the destination directory in the archive</span>
<span class="org-variable-name">DEST_DIR</span>=<span class="org-string">"$ARCHIVE_DIR/$(dirname "$RELATIVE_TARGET_PATH")"</span>

<span class="org-comment-delimiter"># </span><span class="org-comment">Create the destination directory if it doesn't exist</span>
mkdir -p <span class="org-string">"$DEST_DIR"</span>

<span class="org-comment-delimiter"># </span><span class="org-comment">Check if the target is a directory</span>
<span class="org-keyword">if</span> [ -d <span class="org-string">"$TARGET"</span> ]; <span class="org-keyword">then</span>
  <span class="org-comment-delimiter"># </span><span class="org-comment">Use rsync to merge directories if the target is a directory</span>
  rsync -a <span class="org-string">"$TARGET/"</span> <span class="org-string">"$DEST_DIR/$(basename "$TARGET")/"</span>
  <span class="org-comment-delimiter"># </span><span class="org-comment">Remove the original directory after merging</span>
  rm -rf <span class="org-string">"$TARGET"</span>
<span class="org-keyword">else</span>
  <span class="org-comment-delimiter"># </span><span class="org-comment">Move the target to the archive directory if it's a file</span>
  mv <span class="org-string">"$TARGET"</span> <span class="org-string">"$DEST_DIR/"</span>
<span class="org-keyword">fi</span>

<span class="org-builtin">echo</span> <span class="org-string">"Archived '$TARGET' to '$DEST_DIR/'."</span>
</pre>
</div>

</details>

<p>
I also created a little emacs lisp script to archive the open file.
</p>

<details>
<summary>Emacs lisp script</summary>

<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span class="org-keyword">defvar</span> <span class="org-variable-name">my-archive-dir</span> <span class="org-string">"~/archive"</span>
  <span class="org-doc">"Directory where files will be archived."</span>)

(<span class="org-keyword">defun</span> <span class="org-function-name">archiver-archive-open-file</span> ()
  <span class="org-doc">"Move the current file to the archive directory."</span>
  (<span class="org-keyword">interactive</span>)
  (<span class="org-keyword">if</span> (buffer-file-name)
      (<span class="org-keyword">let*</span> ((file-path (buffer-file-name))
             (relative-path (file-relative-name file-path (getenv <span class="org-string">"HOME"</span>)))
             (archive-path (expand-file-name relative-path my-archive-dir)))
        (<span class="org-keyword">if</span> (file-exists-p file-path)
            (<span class="org-keyword">progn</span>
              (save-buffer)
              (make-directory (file-name-directory archive-path) t)
              (rename-file file-path archive-path t)
              (kill-buffer)
              (message <span class="org-string">"Archived: %s"</span> archive-path))
          (message <span class="org-string">"File does not exist: %s"</span> file-path)))
    (message <span class="org-string">"No file is associated with this buffer."</span>)))
</pre>
</div>

</details>
</div>
</div>
<div id="outline-container-org7d3c102" class="outline-2">
<h2 id="org7d3c102">Decluttering my agenda</h2>
<div class="outline-text-2" id="text-org7d3c102">
<p>
The same issue of clutter—the fear of removing things and regretting it—applies to not just files but the <i>contents</i> of files, such as headings in an Org file in Emacs. While Emacs Org-mode <i>does</i> have a built in command for archiving headings, the resulting archive contains a flat list of archived headings. In other words, the original document structure is not preserved. So I created an Emacs command to archive Org agenda headings in an archive file that mirrors the structure of the agenda.
</p>


<div id="org22d7a4f" class="figure">
<p><img src="http://duncanbritt.com/blog/decluttering/emacs-archiver.gif" alt="emacs-archiver.gif" />
</p>
<p><span class="figure-number">Figure 1: </span>Demo of Archiver Package</p>
</div>

<ul class="org-ul">
<li><a href="https://github.com/Duncan-Britt/emacs-archiver" target="_blank">Source</a></li>
</ul>
</div>
<div id="outline-container-org516c30b" class="outline-3">
<h3 id="org516c30b">Installation</h3>
<div class="outline-text-3" id="text-org516c30b">
<p>
Clone the repository in your preferred destination.
</p>
<div class="org-src-container">
<pre class="src src-sh"><span class="org-builtin">cd</span> ~/path/to
git clone https://github.com/Duncan-Britt/emacs-archiver.git
</pre>
</div>

<p>
Add the following to your config, specifying the path to the cloned repository and the path to your agenda archive file.
</p>
<div class="org-src-container">
<pre class="src src-emacs-lisp">(<span class="org-keyword">use-package</span> archiver
  <span class="org-builtin">:load-path</span> <span class="org-string">"~/path/to/emacs-archiver/"</span>
  <span class="org-builtin">:after</span> org
  <span class="org-builtin">:init</span>
  (<span class="org-keyword">setq</span> *archiver-agenda-archive-location*
        (expand-file-name <span class="org-string">"~/path/to/your/agenda_archive.org"</span>))
  <span class="org-builtin">:bind</span>
  (<span class="org-builtin">:map</span> org-mode-map
        (<span class="org-string">"C-c C-x C-a"</span> . archiver-archive-heading)))
</pre>
</div>
</div>
</div>
</div>
]]></description>
</item>
<item>
<title>SeqImprove: Curation of Genetic Circuits</title>
<link>http://duncanbritt.com/blog/seqimprove/seqimprove.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/seqimprove/seqimprove.html</guid>
<pubDate>Sat, 15 Jul 2023 00:00:00 -0600</pubDate>
<description><![CDATA[<p><a href="http://duncanbritt.com/blog/seqimprove/seqimprove.html">Read more</a></p>]]></description>
</item>
<item>
<title>Path Planning By Rapidly Exploring Random Trees</title>
<link>http://duncanbritt.com/blog/path-finding-with-RRT/path-finding-RRT.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/path-finding-with-RRT/path-finding-RRT.html</guid>
<pubDate>Sun, 19 Mar 2023 00:00:00 -0600</pubDate>
<description><![CDATA[<p><a href="http://duncanbritt.com/blog/path-finding-with-RRT/path-finding-RRT.html">Read more</a></p>]]></description>
</item>
<item>
<title>Path Planning With A*</title>
<link>http://duncanbritt.com/blog/path-finding/path-finding.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/path-finding/path-finding.html</guid>
<pubDate>Sun, 12 Mar 2023 00:00:00 -0700</pubDate>
<description><![CDATA[<p><a href="http://duncanbritt.com/blog/path-finding/path-finding.html">Read more</a></p>]]></description>
</item>
<item>
<title>Programming an Autonomous Mobile Robot</title>
<link>http://duncanbritt.com/blog/autonomous-mobile-robot/autonomous-mobile-robot.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/autonomous-mobile-robot/autonomous-mobile-robot.html</guid>
<pubDate>Sun, 15 Jan 2023 00:00:00 -0700</pubDate>
<description><![CDATA[<ul class="org-ul">
<li><p><a href="https://github.com/Duncan-Britt/Space-Grants-Robotics-ACC-22-23" target="_blank">Source Code</a></p></li>
</ul>


<div id="org19bc683" class="figure">
<p><img src="http://duncanbritt.com/blog/autonomous-mobile-robot/images/board.jpg" alt="board.jpg" />
</p>
<p><span class="figure-number">Figure 1: </span>My Arduino Due with magnetometer</p>
</div>

<p>
I'm the lead programmer on the robotics team at school and where working on an autonomous mobile robot. The project is sponsored by NASA's Colorado Space Grants Consortium and our robot will participate in their challenge in April. The involves traversing a variety of outdoor obstacle courses without the use of GPS. What follows is an overview of our in progress program.
</p>
<div id="outline-container-org28cce02" class="outline-2">
<h2 id="org28cce02">Program Overview</h2>
<div class="outline-text-2" id="text-org28cce02">
<div style="background: var(--svg-bg)">

<div id="org37d03a0" class="figure">
<p><img src="http://duncanbritt.com/blog/autonomous-mobile-robot/images/loops.svg" alt="loops.svg" class="org-svg" />
</p>
</div>
</div>

<p>
The program is so far organized into a few loops that run asynchronously. This means that we describe distinct sequences of events which run in parrallel, repeatedly and independently of one another, over different and varying time intervals. These loops can communicate with one another by modifying the variables which comprise the state of the program.
</p>

<p>
So for instance, we have a loop which is concerned with planning the robot's path. It waits for the robot's path to be interrupted by an obstacle and then computes a path towards the goal destination using the robot's belief about its current position and known obstacles. Another loop is concerned with executing this plan. The plan for the robots future motion is part of the shared state of the program, and so the planning loop is able to communicate with the plan execution loop by modifying the plan.
</p>

<p>
The plan consists of a queue of desired destinations, represented as coordinates on a 2D plane. Going from one destination to another is broken down into two steps: First, turn to face the desired destination. Next, go forward until you've gone far enough. The plan execution loop described previously is concerned with deciding that the robot has arrived at its destination and computing the two steps that need to be taken in order to get to the next destination on the path. It modifies the plan by eliminating the next destination in the queue once it has arrived.
</p>

<p>
Another loop is concerned with the execution of the two steps necessary to go from one destination to the next: the rotation and the translation. I've called these two loops the major and minor plan execution loops in the above diagram. The major loop communicates to the minor loop by deciding those two steps, which are represented as poses. A pose combines position with orientation, so it is a 2D coordinate and a rotation with respect to the x axis. The minor loop decides that the next pose has been achieved and removes it from the queue, modifying the state of the program. This is how the minor loop communicates with what I've called the PID control loop, which is concerned with the low level control of the motors for motion control, among other things.
</p>

<p>
The PID loop is always trying to achieve the next goal pose. It uses sensor data, the robots belief about where it is, and the next desired pose to calculate a correction to be applied to the voltages currently being sent to the motor control pins. Every so often, the robot must check its sensors and then reevaluate its belief about where it is. Only then is it in a position to apply a correction to the motor control. It communicates with the other loops by updating the robot's belief about its current position and updating sensor readings.
</p>

<div class="org-src-container">
<label class="org-src-name"><span class="listing-number">Listing 1: </span>In <code>main.ino</code>: The <code>setup()</code> function is invoked once when the Arduino board is turned on. The <code>loop()</code> function is repeatedly invoked for as long as the Arduino board has power.</label><pre class="src src-C++"><span class="org-type">AsyncLoop</span> <span class="org-variable-name">loop_obstacle</span>;
<span class="org-type">AsyncLoop</span> <span class="org-variable-name">loop_positions</span>;
<span class="org-type">AsyncLoop</span> <span class="org-variable-name">loop_poses</span>;
<span class="org-type">AsyncLoop</span> <span class="org-variable-name">loop_pid</span>;

<span class="org-type">void</span> <span class="org-function-name">setup</span>() 
{
    <span class="org-comment-delimiter">//</span><span class="org-comment">... omitted</span>
    loop_obstacle
        .when(path_interrupted)
        .then(stop) <span class="org-comment-delimiter">// </span><span class="org-comment">empty the position queue and enqueue nearby position</span>
        .when((<span class="org-type">void</span>*)+[]() -&gt; <span class="org-type">bool</span> { <span class="org-comment-delimiter">// </span><span class="org-comment">wait for the robot to stop</span>
            <span class="org-keyword">return</span> idx_pose_array == 1 &amp;&amp; pose_achieved();
        })
        .then(reroute);

    loop_positions
        .when(position_achieved)
        .then((<span class="org-type">void</span>*)+[]() -&gt; <span class="org-type">void</span> { <span class="org-comment-delimiter">// </span><span class="org-comment">Enqueue poses, dequeue position.</span>
            <span class="org-keyword">if</span> (<span class="org-negation-char">!</span>(position_queue.empty())) {
                Pose_enqueue_transition(&amp;pose_current, position_queue.front(), pose_array);
                idx_pose_array = 0;
                position_queue.dequeue();
            }
        });

    loop_poses
        .when(pose_achieved)
        .then((<span class="org-type">void</span>*)+[]() -&gt; <span class="org-type">void</span> { <span class="org-comment-delimiter">// </span><span class="org-comment">dequeue pose</span>
            idx_pose_array = 1; <span class="org-comment-delimiter">// </span><span class="org-comment">go to the second pose</span>
        });

    loop_pid
        .when(time_elapsed_ms_50)
        .then(update_perception_localize_and_pid);
}

<span class="org-type">void</span> <span class="org-function-name">loop</span>() 
{
    loop_obstacle();
    loop_positions();
    loop_poses();
    loop_pid();
}
</pre>
</div>

<p>
In the following sections I attempt to describe the components of the program in more detail.
</p>
</div>
</div>
<div id="outline-container-org871824f" class="outline-2">
<h2 id="org871824f">Path Planning</h2>
<div class="outline-text-2" id="text-org871824f">
<p>
We need to figure out how to decide whether an obstacle has been detected and whether it interrupts our path forward, as well as where we believe the obstacle is. We also need to figure out how to persist this knowledge in a way that will consume the least amount of memory.
</p>

<p>
Equipped with knowledge of where obstacles lie, we can model the landscape surrounding the robot as an occupancy grid.
</p>


<div id="org4fdda3c" class="figure">
<p><img src="http://duncanbritt.com/blog/autonomous-mobile-robot/images/occupancy-map.png" alt="occupancy-map.png" />
</p>
<p><span class="figure-number">Figure 2: </span>This image found <a href="https://iis-projects.ee.ethz.ch/index.php?title=Autonomous_Obstacle_Avoidance_with_Nano-Drones_and_Novel_Depth_Sensors">online</a> shows an example of an occupancy grid.</p>
</div>

<p>
In the field of mobile robotics, there are a variety of commonly used path planning algorithms. Originally I implemented one of them called <a href="https://www.youtube.com/watch?v=-L-WgKMFuhE&amp;t=227s">A*</a> (A-Star). But I quickly ran into the limits of the Arduino Uno's memory capacity so I've started implementing <a href="https://ai.stackexchange.com/questions/8821/how-is-iterative-deepening-a-better-than-a">alternative</a> <a href="https://ieeexplore.ieee.org/document/6617944">methods</a> which I expect will consume less memory.
</p>

<p>
For the sake of testing these algorithms and visualizing the paths they produce, I've written some code that allows us to be able to create an occupancy grid in the Arduino's memory from human readable text, and to be able to print a visual representation of the path it produces. Here's a demonstration in which we ask it to find a path from the top right corner to the bottom left:
</p>
<div class="org-src-container">
<pre class="src src-C++"><span class="org-preprocessor">#define</span> <span class="org-variable-name">DEBUG_GRID_STRING</span> <span class="org-string">"\</span>
<span class="org-string">  ........\n\</span>
<span class="org-string">  ........\n\</span>
<span class="org-string">  ...##...\n\</span>
<span class="org-string">  ....#...\n\</span>
<span class="org-string">  ....#...\n\</span>
<span class="org-string">  ....##..\n\</span>
<span class="org-string">  ........\n\</span>
<span class="org-string">  ........"</span>

<span class="org-comment-delimiter">// </span><span class="org-comment">testing our implementation of the A* search algorithm on an occupancy grid</span>
<span class="org-type">void</span> <span class="org-function-name">test_a_star</span>() 
{
    <span class="org-type">Grid</span> <span class="org-variable-name">grid</span>;
    grid_init_str(DEBUG_GRID_STRING, &amp;grid);        
    grid_print(&amp;grid);
    DEBUG_PRINTLN(F(<span class="org-string">""</span>));
    <span class="org-type">uint16_t</span> <span class="org-variable-name">path</span>[MAX_PATH_SIZE]; <span class="org-comment-delimiter">// </span><span class="org-comment">[0, 65535]</span>
    <span class="org-type">uint8_t</span> <span class="org-variable-name">path_size</span> = 0; <span class="org-comment-delimiter">// </span><span class="org-comment">[0, 255]</span>
    grid_find_path(&amp;grid, 7, 56, path, &amp;path_size, MAX_PATH_SIZE);
    grid_print_path(&amp;grid, path, path_size);
    free(grid.obstacles);
}
</pre>
</div>
<p>
The #'s represent obstacles and the .'s represent open space. It produces the following output in which @'s are positions along our path:
</p>
<div class="org-src-container">
<pre class="src src-nil">. . . . . . . . 
. . . . . . . . 
. . . # # . . . 
. . . . # . . . 
. . . . # . . . 
. . . . # # . . 
. . . . . . . . 
. . . . . . . . 

. . . . . . . @ 
. . . @ @ @ @ . 
. . @ # # . . . 
. . @ . # . . . 
. . @ . # . . . 
. . @ . # # . . 
. @ . . . . . . 
@ . . . . . . . 
</pre>
</div>

<p>
Based on the memory available to us, we'll have to decide how large to make the grid and how many \(\mathrm{cm}^2\) can be represented by a single grid space. More fidelity is better, but consumes more memory. Given a limited grid size, we'll also have to choose where to position the grid in the global coordinate system. One note about the grid: I was thinking perhaps we should expand the size of obstacles in the grid to account for the size of the robot and then treat the robot as a point mass.
</p>
</div>
</div>
<div id="outline-container-org3179779" class="outline-2">
<h2 id="org3179779">Grid Implementation</h2>
<div class="outline-text-2" id="text-org3179779">
<p>
The grid is implemented as an array of bits. 0's are open spaces and 1's are obstacles:
</p>
<div class="org-src-container">
<pre class="src src-nil">0 0 0 0 0
0 1 1 0 0
0 0 1 0 0
0 0 0 0 0
</pre>
</div>
<p>
The indices of the above grid are laid out as follows:
</p>
<div class="org-src-container">
<pre class="src src-nil"> 0  1  2  3  4
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
</pre>
</div>

<div class="org-src-container">
<pre class="src src-C++"><span class="org-keyword">typedef</span> <span class="org-keyword">struct</span> <span class="org-type">Grid</span> {
    <span class="org-type">uint8_t</span>* <span class="org-variable-name">obstacles</span>; <span class="org-comment-delimiter">// </span><span class="org-comment">bit array</span>
    <span class="org-type">uint8_t</span> <span class="org-variable-name">cols</span>; <span class="org-comment-delimiter">// </span><span class="org-comment">[0, 255]</span>
    <span class="org-type">uint8_t</span> <span class="org-variable-name">rows</span>; <span class="org-comment-delimiter">// </span><span class="org-comment">[0, 255]</span>
} <span class="org-type">Grid</span>;
</pre>
</div>
<p>
The smallest data type available to us is an 8-bit integer, but we only need one bit to represent whether a given grid space is occupied. So, to make the grid take up as little memory as possible, a single unsigned 8-bit integer is used to represent 8 grid spaces, and the whole grid is just a one dimensional array of unsigned 8-bit integers.
</p>

<p>
One of the things to consider is perhaps having a <a href="https://ieeexplore.ieee.org/document/9304571">non uniform cell representation</a> in our grid, for the sake of saving memory and gaining a higher fidelity representation of the surroundings.
</p>


<div id="orga62c8eb" class="figure">
<p><img src="http://duncanbritt.com/blog/autonomous-mobile-robot/images/non-uniform-grid.jpeg" alt="non-uniform-grid.jpeg" />
</p>
</div>
</div>
</div>
<div id="outline-container-org6955eb0" class="outline-2">
<h2 id="org6955eb0">PID Control</h2>
<div class="outline-text-2" id="text-org6955eb0">
<p>
The PID algorithm can be used to deal with the low level motor control of our robot. We can adjust the speed and direction of the motors using a function of the magnitude and direction of the discrepancy between where the robot is and where it wants to be at any given time, typically referred to as the <b>error value</b> in the context of PID. In addition to the error value \(e(t)\), PID also uses the accumulation of these error values over time \(\int{e(t)dt}\), and the rate at which the discrepancy is changing \(\frac{de}{dt}\).
</p>

<p>
\[ u(t) = K_p e(t) + K_i \int e(t) dt + K_d \frac{de}{dt} \]
where \(K_p\), \(K_i\), and \(K_d\) are constants that give weight to each of the terms, and must be decided through trial and error. PID stands for proportional, integral, derivative and is named for each of the 3 terms in the equation.
</p>

<p>
In code, the integral term can simply be a running total of the error values, and the derivative term would be the difference between the current error value and the previous error value from say, 50 ms ago.
</p>
<div class="org-src-container">
<pre class="src src-C++"><span class="org-comment-delimiter">//</span><span class="org-comment">... somewhere in our code, hypothetically:</span>
e_integral += e_current * timestep;
e_derivative = (e_current - e_previous) / timestep;
</pre>
</div>
<p>
We still need to implement all of this. These two videos do a good job of explaining PID control:
</p>
<ul class="org-ul">
<li>Mobile Robot Systems Course - Lecture 3: Motion Control 58:52-1:10:04 <a href="https://youtu.be/tocxIukOa-I?t=3532">https://youtu.be/tocxIukOa-I?t=3532</a></li>
<li>PID Control: A brief introduction <a href="https://youtu.be/UR0hOmjaHp0">https://youtu.be/UR0hOmjaHp0</a></li>
</ul>
</div>
<div id="outline-container-org7281b4a" class="outline-3">
<h3 id="org7281b4a">Motor control</h3>
<div class="outline-text-3" id="text-org7281b4a">
<p>
What I have implemented so far is an interface for controlling the motors. First, allow me to try and motivate the need for such an interface.
</p>

<p>
There may be up to 3 pins associated with each motor, based on what I recall from the motor shields we've looked at. To go forward, we send voltage to the forward pin, no voltage to the backward pin, and send some amount of voltage to the analog speed pin which tells the motor how fast to go. And likewise, to go backward, we would send voltage to the backward pin, but not the forward pin for the motor. (I think motors on the same left/right side should share a speed pin). It's kind of a mouthful just to tell one motor to go. When we apply voltage to an analog pin (for controlling speed), we give it a number between 0 and 255 (inclusive) like so: <code class="src src-c++">analogWrite(pinNumber, speedNumber);</code>. But there is some speed values in the range that aren't large enough to produce any motion.
</p>

<p>
What I thought would be really nice is if we could tell the motors what to do with a single number between -100 and 100, where 100 is the max speed, 1 is the min speed in the forward direction, 0 is off, and negative numbers are for reversing the motors. So here's an example of one such function that does that for the front left motor:
</p>
<div class="org-src-container">
<pre class="src src-C++"><span class="org-type">void</span> <span class="org-function-name">motors_set_velocity_left_front</span>(<span class="org-type">char</span> <span class="org-variable-name">velocity</span>)
{
    velocity = normalize(velocity);

    <span class="org-keyword">if</span> (velocity == 0) {
        digitalWrite(pin_left_front_fw, LOW);
        digitalWrite(pin_left_front_bw, LOW);
        analogWrite(pin_left_front_speed, 0);
    }
    <span class="org-keyword">else</span> <span class="org-keyword">if</span> (velocity &gt; 0) {
        digitalWrite(pin_left_front_fw, HIGH);
        digitalWrite(pin_left_front_bw, LOW);
        analogWrite(pin_left_front_speed, voltage_of_speed((<span class="org-type">byte</span>)abs(velocity)));
    } <span class="org-keyword">else</span> {
        digitalWrite(pin_left_front_fw, LOW);
        digitalWrite(pin_left_front_bw, HIGH);
        analogWrite(pin_left_front_speed, voltage_of_speed((<span class="org-type">byte</span>)abs(velocity)));
    }

    current_velocity_left_front = velocity;
}
</pre>
</div>
<p>
It takes a number in the range -100 to 100 and maps it to the appropriate speed in the range [0, 255],
as well as setting the direction of the motors.
</p>

<p>
We also have functions for incrementing the velocity of the motors by a certain amount [-100, 100].
</p>
<div class="org-src-container">
<pre class="src src-C++"><span class="org-comment-delimiter">// </span><span class="org-comment">Increment (or decrement if argument is negative) the speed of the motors.</span>
<span class="org-type">void</span> <span class="org-function-name">motors_increment_velocity_left</span>(<span class="org-keyword">const</span> <span class="org-type">char</span> <span class="org-variable-name">increment</span>)
{
    motors_set_velocity_left_front(current_velocity_left_front + increment);
    motors_set_velocity_left_back(current_velocity_left_back + increment);
}
</pre>
</div>
<p>
This is the interface that I expect to be used along with PID. PID tells us how to adjust the current speed and direction of the motors.
</p>
</div>
</div>
</div>
<div id="outline-container-orgd69fd2e" class="outline-2">
<h2 id="orgd69fd2e">Perception &amp; Localization</h2>
<div class="outline-text-2" id="text-orgd69fd2e">
<p>
For any of the sensors we end up using, we'll need to write code that we can use to query the sensor for data. Currently we have a third party library for the Sharp IR sensor which makes getting distance data as easy as <code>sensor_IR.distance()</code>.
</p>

<p>
There's a very real possibility that our estimate of our current position relative to the starting point won't be great and will become terrible as time goes on. The thing that is really important though is that we can maintain our sense of direction, and that's why a compass would be valuable. This way, we can make sure we are at least headed in the right general direction.
</p>
</div>
</div>
<div id="outline-container-orgc2f21c7" class="outline-2">
<h2 id="orgc2f21c7">UPDATE: The challenge at the sand dunes.</h2>
<div class="outline-text-2" id="text-orgc2f21c7">
<p>
We didn't end up having time to implement all the feature I had planned for. A week before the challenge in April, we discovered the robot lacked sufficient torque to be able to turn in place. There wasn't enough time left to fix the hardware, but I could make the robot do wide turns by applying more power to either side. The plan became to have the robot do many-point turns.
</p>


<div id="org2913d1a" class="figure">
<p><img src="http://duncanbritt.com/blog/autonomous-mobile-robot/images/wide_turns.gif" alt="wide_turns.gif" width="300px" />
</p>
<p><span class="figure-number">Figure 3: </span>Testing out many-point turns</p>
</div>

<p>
We also had yet to attach wheel encoders to the robot, so without the ability to localize or turn in place, I set about an entirely different strategy which involved having the robot attempt to go in the direction that was forward when the robot was turned on, and avoiding abstacles by turning away for a short time.
</p>


<div id="org2f5d026" class="figure">
<p><img src="http://duncanbritt.com/blog/autonomous-mobile-robot/images/state-diagram.png" alt="state-diagram.png" />
</p>
<p><span class="figure-number">Figure 4: </span>State diagram</p>
</div>

<p>
When we got to the sand dunes we realized the courses were much narrower and shorter than we had anticipated. To accomodate this, I rewrote the driving script for our program several times while at the sand dunes, over the course of about 4 hours. Another source of difficulty we discovered at the dunes was that our IR sensors returned noisy distance readings and regularly picked up the ground, leading to false positives in obstacle detection. To deal with this, I attempted to avoid false pasitives by taking 10 consecutive measurements and only considering an obstacle detected if all measurements were within the threshold. It worked reasonably well, but we still didn't have enough space to turn with digging the robot into the sand and getting stuck.
</p>

<details>
<summary>The driving script for our last attempt</summary>
<div class="org-src-container">
<pre class="src src-c++">loop_main
.when((<span class="org-type">void</span>*)time_elapsed_ms_50)
.then((<span class="org-type">void</span>*)+[]() -&gt; <span class="org-type">void</span> {
    <span class="org-type">float</span> <span class="org-variable-name">xl</span> = (<span class="org-type">float</span>)sensor_left.distance();
    <span class="org-type">float</span> <span class="org-variable-name">xr</span> =  (<span class="org-type">float</span>)sensor_right.distance();
    <span class="org-type">int</span> <span class="org-variable-name">current_left</span> = xl - ((0 - 3) * pow(10.0, 14.0) * pow((xl + 66.0), -7.42)) + 1.7;
    <span class="org-type">int</span> <span class="org-variable-name">current_right</span> = xr - 1.718 * sin((xr + 40.8) / (11.7802)) + 1.26; <span class="org-comment-delimiter">// </span><span class="org-comment">sensor calibrations</span>
    <span class="org-keyword">for</span> (<span class="org-type">int</span> <span class="org-variable-name">i</span> = 9; i &gt; 0; i--) {
        prev_left[i] = prev_left[i - 1];
        prev_right[i] = prev_right[i - 1];
    }

    prev_left[0] = current_left;
    prev_right[0] = current_right;

    <span class="org-type">bool</span> <span class="org-variable-name">left_detected</span> = <span class="org-constant">true</span>;
    <span class="org-type">bool</span> <span class="org-variable-name">right_detected</span> = <span class="org-constant">true</span>;
    <span class="org-keyword">for</span> (<span class="org-type">int</span> <span class="org-variable-name">i</span> = 0; i &lt; 10; ++i) {
        <span class="org-keyword">if</span> (prev_left[i] &gt; 25) {
            left_detected = <span class="org-constant">false</span>;                  
        }

        <span class="org-keyword">if</span> (prev_right[i] &gt; 25) {
            right_detected = <span class="org-constant">false</span>;
        }

        <span class="org-keyword">if</span> ((<span class="org-negation-char">!</span>left_detected) || (<span class="org-negation-char">!</span>right_detected)) {
            <span class="org-keyword">break</span>;
        } 
    }

    <span class="org-keyword">if</span> (left_detected) { <span class="org-comment-delimiter">// </span><span class="org-comment">back up to the left</span>
        motors_set_velocity_left(-10);
        motors_set_velocity_right(-100);
        delay(2000);
    } <span class="org-keyword">else</span> <span class="org-keyword">if</span> (right_detected) { <span class="org-comment-delimiter">// </span><span class="org-comment">back up to the right</span>
        motors_set_velocity_right(-10);
        motors_set_velocity_left(-100);
        delay(2000);
    }
    motors_set_velocity(100);
 });
</pre>
</div>
</details>

<p>
We were able to clear 3 of 5 obstacle courses, and we won an award for my navigation system despite that it was not in use at the dunes.
</p>


<div id="orgc810a4f" class="figure">
<p><img src="http://duncanbritt.com/blog/autonomous-mobile-robot/images/ida-star.gif" alt="ida-star.gif" />
</p>
<p><span class="figure-number">Figure 5: </span>IDA* algorithm test, ran on my Arduino Uno.</p>
</div>
</div>
</div>
]]></description>
</item>
<item>
<title>Splice: An HTML templating language</title>
<link>http://duncanbritt.com/blog/splice/splice.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/splice/splice.html</guid>
<pubDate>Wed, 19 Jan 2022 00:00:00 -0700</pubDate>
<description><![CDATA[<ul class="org-ul">
<li><a href="https://duncan-britt.github.io/splice-docs/" target="_blank">Docs</a></li>
<li><a href="https://github.com/Duncan-Britt/Splice-Lang" target="_blank">Repo</a></li>
</ul>
<div id="outline-container-orgabe76bd" class="outline-2">
<h2 id="orgabe76bd">Overview</h2>
<div class="outline-text-2" id="text-orgabe76bd">
<p>
I made an HTML templating language that I call Splice. It was a fun and educational exercise. Splice supports nesting, partial templates, iterators, conditionals, variable assignment, local scope, comments, escape characters, and escapes HTML by default. In its minified form, it is only 3.06 KB uncompressed, and has no dependencies.
</p>

<p>I've written extensively about how to use Splice, and that writing is available on the <a href="https://duncan-britt.github.io/splice-docs/" target="_blank">documentation website</a>. I will use this space to talk about the implementation of the language, design process/choices, challenges, and open issues.</p>
</div>
</div>
<div id="outline-container-orgb4a58f2" class="outline-2">
<h2 id="orgb4a58f2">Abstract Syntax Tree (AST)</h2>
<div class="outline-text-2" id="text-orgb4a58f2">
<p>
The AST for Splice begins not with a single root node, but with a collection of its children - the root node is imaginary. There are three types of nodes in the AST:
</p>

<ul class="org-ul">
<li>text</li>
<li>binding</li>
<li>operator</li>
</ul>

<p>
Text nodes and binding nodes are leaf nodes, whereas operator nodes have a body property which is a subtree. (I think of the body as just a special kind of argument that always comes last). For example, the AST for the following splice template:
</p>

<div class="org-src-container">
<pre class="src src-html">&lt;<span class="org-function-name">p</span>&gt;Hello, (: username :)! Here are your todos:&lt;/<span class="org-function-name">p</span>&gt;
&lt;<span class="org-function-name">ul</span>&gt;
  (:~ each todos as 'todo {
  &lt;<span class="org-function-name">li</span>&gt;
    &lt;<span class="org-function-name">h2</span>&gt;<span class="org-underline"><span class="org-bold-italic">(: todo.name :)</span></span>&lt;/<span class="org-function-name">h2</span>&gt;
    &lt;<span class="org-function-name">p</span>&gt;(: todo.description :)&lt;/<span class="org-function-name">p</span>&gt;
  &lt;/<span class="org-function-name">li</span>&gt;
  }:)
&lt;/<span class="org-function-name">ul</span>&gt;
</pre>
</div>

<p>
would look something like this:
</p>

<div style="background: var(--svg-bg); padding: 4px;">

<div id="orgf9d9eb9" class="figure">
<p><img src="http://duncanbritt.com/blog/splice/images/ast.svg" alt="ast.svg" class="org-svg" width="60%" />
</p>
<p><span class="figure-number">Figure 1: </span>An example Splice AST</p>
</div>
</div>
</div>
</div>
<div id="outline-container-orgc8a960c" class="outline-2">
<h2 id="orgc8a960c">Lexer &amp; Parser</h2>
<div class="outline-text-2" id="text-orgc8a960c">
<p>
The lexer and parser work together to turn the former template into the latter AST. The job of a lexer is to split up the text of a program into relevant tokens, and the job of a parser is to create the AST from those tokens. In my program, these roles are intertwined- tokens are parsed as soon as they are identified. My lexing/parsing function takes the template and returns an AST. Within, it runs a loop which invokes a function that identifies a single token, parses it, and returns the remaining template.
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-comment-delimiter">// </span><span class="org-comment">parse :: String -&gt; Array{Object}</span>
<span class="org-keyword">function</span> <span class="org-function-name">parse</span>(<span class="org-variable-name">template</span>) {
  <span class="org-keyword">const</span> <span class="org-variable-name">ast</span> = [];
&#8203;
  <span class="org-keyword">while</span> (template) {
    template = parseToken(template, ast);
  }
&#8203;
  <span class="org-keyword">return</span> ast;
}
</pre>
</div>

<p>
When an operator body token is identified, the parser simply creates an AST from the operator body token by recursively invoking the main lexing/parsing function. The recursive nature of the lexer/parser reflects the recursive nature of the syntax tree- operator bodies are subtrees.
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-comment-delimiter">// </span><span class="org-comment">parseFunction :: String -&gt; Array{String, Object}</span>
<span class="org-keyword">function</span> <span class="org-function-name">parseFunction</span>(<span class="org-variable-name">template</span>) {
  <span class="org-comment-delimiter">//</span><span class="org-comment">... code omitted for brevity</span>
  [ token, bodyAST ] = parseBody(template);
  <span class="org-comment-delimiter">//</span><span class="org-comment">...</span>
  <span class="org-keyword">const</span> <span class="org-variable-name">expr</span> = {
    type: <span class="org-string">'op'</span>,
    name: op,
    args: args,
    body: bodyAST,
  };
  <span class="org-comment-delimiter">//</span><span class="org-comment">...</span>
}
&#8203;
<span class="org-comment-delimiter">// </span><span class="org-comment">parseBody :: String -&gt; Array{String, Array{Object}}</span>
<span class="org-keyword">function</span> <span class="org-function-name">parseBody</span>(<span class="org-variable-name">template</span>) {
  <span class="org-comment-delimiter">//</span><span class="org-comment">...</span>
  <span class="org-keyword">return</span> [resultToken, parse(body)];
}
</pre>
</div>
</div>
</div>
<div id="outline-container-org743041d" class="outline-2">
<h2 id="org743041d">Generator</h2>
<div class="outline-text-2" id="text-org743041d">
<p>
Now the hard work is done! All thats left is to turn the tree into text again. A reminder, when someone uses the compiler, they pass an object with the data to be filled into the template. That object can be thought of as the global scope for the Splice program. The job of the generator is to use the scope and the AST to render the final text output.
</p>

<p>
The generator has knowledge of the three node types. For operator nodes, it must return the result of invoking the associated function, as all valid operators in the language have an internal function associated with them.
</p>

<p>
Valid bindings refer to some property of the scope object, so all generator has to do is look up that property for a given binding node and return it. And of course, for text nodes, just return text!
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-comment-delimiter">// </span><span class="org-comment">evaluateAll :: Array, Object -&gt; String</span>
<span class="org-keyword">function</span> <span class="org-function-name">evaluateAll</span>(<span class="org-variable-name">ast</span>, <span class="org-variable-name">scope</span>) {
  <span class="org-keyword">return</span> ast.reduce((html, expr) =&gt; html + evaluate(expr, scope), <span class="org-string">""</span>);
}
&#8203;
<span class="org-comment-delimiter">// </span><span class="org-comment">evaluate :: Object, Object -&gt; String</span>
<span class="org-keyword">function</span> <span class="org-function-name">evaluate</span>(<span class="org-variable-name">expr</span>, <span class="org-variable-name">scope</span>) {
  <span class="org-keyword">switch</span> (expr.type) {
    <span class="org-keyword">case</span> <span class="org-string">"op"</span>:
      <span class="org-keyword">return</span> templateFns[expr.name](scope, ...expr.args, expr.body);
    <span class="org-keyword">case</span> <span class="org-string">"binding"</span>:
      <span class="org-keyword">let</span> <span class="org-variable-name">value</span> = expr.chain.reduce((data, prop) =&gt; data[prop], scope[expr.name]);
      <span class="org-keyword">if</span> (<span class="org-keyword">typeof</span> value == <span class="org-string">'string'</span>) {
        <span class="org-keyword">return</span> expr.escape ? escapeHTML(value) : value;
      }
&#8203;
      <span class="org-keyword">return</span> value;
    <span class="org-keyword">case</span> <span class="org-string">'text'</span>:
      <span class="org-keyword">return</span> escapeChars(expr.value);
  }
}
</pre>
</div>
</div>
</div>
<div id="outline-container-org6160d4b" class="outline-2">
<h2 id="org6160d4b">My Process</h2>
<div class="outline-text-2" id="text-org6160d4b">
<p>
My original design for the syntax didn't stick. It looked like this:
</p>

<div class="org-src-container">
<pre class="src src-nil">&lt;&lt;~ each madlibs &gt;&gt;
  &lt;p&gt;The &lt;&lt; $.adjective &gt;&gt; &lt;&lt; $.noun &gt;&gt; &lt;&lt; $.verb &gt;&gt;&lt;/p&gt;
&lt;&lt; end &gt;&gt;
</pre>
</div>

<p>
I got as far as making a prototype documentation site but decided I didn't love the amount of angle brackets. It wasn't much trouble to change the syntax, but even so, it goes to show that it's worthwhile to make sure you're solving the right problem before you start coding.
</p>

<p>
For the implementation, I started by hardcoding a prototype AST as well as a test 'scope'- a set of data with which to test the compiler. Then I went on to writing the generator of the language. I think this was wise because it allowed me to easily modify the AST to suit the needs of the generator when I discovered something needed to change, without having to rewrite components of the parser.
</p>
</div>
</div>
<div id="outline-container-org625d74d" class="outline-2">
<h2 id="org625d74d">Challenges</h2>
<div class="outline-text-2" id="text-org625d74d">
<p>
After creating the documentation website using Splice and thinking that it was good to go, I ventured to try opening the website in Safari, and lo and behold, the site crashed immediately. I learned the hard way that not all browsers support look-behinds in regular expressions, because I had 49 of them in my Splice compiler.
</p>

<p>
The need for these look-behinds in my regular expressions was to avoid my escape character: \. This meant that I had to replace much of the logic for tokenization without the benefit of regular expressions. On the bright side, I think the readability of my code has benefited significantly from this change.
</p>

<p>
To do this, I wrote a helper function to do most of the heavy lifting:
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-comment-delimiter">// </span><span class="org-comment">strTok :: String, String -&gt; String, String</span>
<span class="org-keyword">function</span> <span class="org-function-name">strTok</span>(<span class="org-variable-name">text</span>, <span class="org-variable-name">endChars</span>, <span class="org-variable-name">chop</span> = <span class="org-constant">false</span>) {
  <span class="org-keyword">let</span> <span class="org-variable-name">i</span> = 0;
  <span class="org-keyword">let</span> <span class="org-variable-name">j</span> = endChars.length;
  <span class="org-keyword">while</span> (j &lt;= text.length) {
    <span class="org-keyword">if</span> (text.slice(i, j) == endChars &amp;&amp; text.slice(i-1, j) != <span class="org-string">'\\'</span> + endChars) {
      <span class="org-keyword">if</span> (chop) {
        <span class="org-keyword">return</span> [text.slice(0, i), text.slice(i + endChars.length)];
      } <span class="org-keyword">else</span> {
        <span class="org-keyword">return</span> [text.slice(0, i), text.slice(i)];
      }
    }
    i++;
    j++;
  }
  <span class="org-keyword">return</span> [text, <span class="org-string">''</span>];
}
</pre>
</div>

<p>
To get a token and the remaining template it can be used like this:
</p>

<div class="org-src-container">
<pre class="src src-javascript">[ token, template ] = strTok(template, <span class="org-string">'(:'</span>);
</pre>
</div>
</div>
</div>
<div id="outline-container-org6db941e" class="outline-2">
<h2 id="org6db941e">Open issues</h2>
<div class="outline-text-2" id="text-org6db941e">
<p>
It would be good to enable pre-compilation of the templates to enable faster performance. My idea is to have an executable that will parse the template(s) within an html file and compile the syntax tree into javascript code, and then write it to a file. The resulting js file would contain a function which contains the syntax tree written as object/array/string literals. That way there is no parsing client-side, only compilation to html.
</p>

<p>
Some other things to work on:
</p>

<ul class="org-ul">
<li>improving the error messages for the language</li>
<li>writing more extensive tests</li>
<li>enabling a user to register a helper function</li>
<li>enable syntax highlighting for the atom text editor</li>
</ul>
</div>
</div>
]]></description>
</item>
<item>
<title>Software Generated Word Ladder Puzzles - Web App</title>
<link>http://duncanbritt.com/blog/software-generated-word-ladder-puzzles-and-web-app/software-generated-word-ladder-puzzles-and-web-app.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/software-generated-word-ladder-puzzles-and-web-app/software-generated-word-ladder-puzzles-and-web-app.html</guid>
<pubDate>Wed, 12 Jan 2022 00:00:00 -0700</pubDate>
<description><![CDATA[<ul class="org-ul">
<li><a href="https://github.com/Duncan-Britt/word_ladders#readme" target="_blank">Repo</a></li>
</ul>


<div id="org2cf8266" class="figure">
<p><img src="http://duncanbritt.com/blog/software-generated-word-ladder-puzzles-and-web-app/word-ladders.gif" alt="word-ladders.gif" width="auto" height="500px" />
</p>
<p><span class="figure-number">Figure 1: </span>Demo</p>
</div>
<div id="outline-container-org3b762b8" class="outline-2">
<h2 id="org3b762b8">Overview</h2>
<div class="outline-text-2" id="text-org3b762b8">
<p>
This web app generates word ladders and asks the user to solve them within a maximum number of steps. The puzzles are generated by the server in response to a request and stored in session data. At a high level, the word ladder puzzles are generated by
</p>

<ol class="org-ol">
<li>making a random word ladder using the <a href="https://github.com/filiph/english_words" target="_blank">5000 most common English words</a></li>
<li>finding the shortest path between those first and last words in the ladder using only the 5000 most common English words</li>
</ol>

<p>
The length of this shortest path determines the maximum number of steps for the user to solve the puzzle.
</p>
</div>
<div id="outline-container-org54f10c1" class="outline-3">
<h3 id="org54f10c1">Additional Features</h3>
<div class="outline-text-3" id="text-org54f10c1">
<ul class="org-ul">
<li>Signup, Login/Logout, Edit/Delete Account</li>
<li>History of a user's previous solutions</li>
<li>Leaderboard</li>
</ul>
</div>
</div>
</div>
<div id="outline-container-org7ee8808" class="outline-2">
<h2 id="org7ee8808">Technologies Used</h2>
<div class="outline-text-2" id="text-org7ee8808">
<p>The backend for the Web App is written in Ruby and uses
<a href="https://sinatrarb.com/intro.html" target="_blank">Sinatra</a>, <a href="https://ruby-doc.org/stdlib-2.7.1/libdoc/erb/rdoc/ERB.html" target="_blank">ERB</a>, and a <a href="https://www.postgresql.org/" target="_blank">PostgreSQL</a> database.</p>
</div>
</div>
<div id="outline-container-orga75d0fc" class="outline-2">
<h2 id="orga75d0fc">Gameplay</h2>
<div class="outline-text-2" id="text-orga75d0fc">
<p>
User input steps are considered valid if
</p>

<ol class="org-ol">
<li>there is one letter of difference between the step and the previous step</li>
<li>and the word can be found among the <a href="https://github.com/cmusphinx/cmudict" target="_blank">200,000 most commonly used English words.</a></li>
</ol>
</div>
<div id="outline-container-orgb224f9e" class="outline-3">
<h3 id="orgb224f9e">Examples:</h3>
<div class="outline-text-3" id="text-orgb224f9e">
<p class="verse">
buy =&gt; buys: valid<br />
buy =&gt; bus: valid<br />
buy =&gt; busy: valid<br />
busy =&gt; buoy: valid<br />
has =&gt; as: valid<br />
use =&gt; bus: invalid<br />
abuse =&gt; bus: invalid<br />
</p>
</div>
</div>
</div>
<div id="outline-container-org3f1c97e" class="outline-2">
<h2 id="org3f1c97e">Generating Puzzles</h2>
<div class="outline-text-2" id="text-org3f1c97e">
<p>
I parsed the data from a csv file of 5,000 most commonly used English words into a graphical representation of the data, which I then serialized to a YAML file so that my ruby code can more efficiently recreate it. Each vertex in the graph represents a word. The neighbors of every vertex in the graph are the vertices whose word is "adjacent" to the word stored by the vertex.
</p>

<div style="background: var(--svg-bg)">

<div id="orgaa3ae2e" class="figure">
<p><img src="http://duncanbritt.com/blog/software-generated-word-ladder-puzzles-and-web-app/images/graph.svg" alt="graph.svg" class="org-svg" />
</p>
<p><span class="figure-number">Figure 2: </span>"The" and its neighbors.</p>
</div>
</div>

<p>
Among my 5k words, it is possible find two words between which there simply is no path. So in order to not waste time solving for the shortest path between two words for which no path exists, my program first creates a ladder randomly.
</p>

<p>
Then, my program takes the first and last words from the random ladder, ignores the rest, and attempts to find the shortest path between them using a breadth first search of the graph. If it takes too long, (if the queue is getting too long) it will inform the calling method which will try again with an entirely new random word ladder.
</p>

<div class="org-src-container">
<pre class="src src-ruby"><span class="org-keyword">class</span> <span class="org-type">Vertex</span>
  <span class="org-comment-delimiter">#</span><span class="org-comment">...</span>
  <span class="org-keyword">def</span> <span class="org-function-name">traverse</span>(end_point)
    <span class="org-keyword">return</span> [<span class="org-keyword">self</span>.data, end_point.data] <span class="org-keyword">if</span> <span class="org-keyword">self</span>.neighbors.include? end_point
    &#8203;
    queue = [[<span class="org-keyword">self</span>]]
    <span class="org-keyword">while</span> (queue.length != 0)
      <span class="org-keyword">if</span> queue.length &gt; 1_000_000
        <span class="org-keyword">return</span> <span class="org-constant">:timeout</span>
      <span class="org-keyword">end</span>
      path = queue.shift
      node = path[-1]
      <span class="org-keyword">return</span> path.map { |n| n.data } <span class="org-keyword">if</span> node == end_point
      &#8203;
      node.neighbors.each <span class="org-keyword">do</span> |neighbor|
        <span class="org-keyword">next</span> <span class="org-keyword">if</span> path.include?(neighbor)
        new_path = path.dup
        new_path &lt;&lt; neighbor
        queue.push(new_path)
      <span class="org-keyword">end</span>
    <span class="org-keyword">end</span>
  <span class="org-keyword">end</span>
  <span class="org-comment-delimiter">#</span><span class="org-comment">...</span>
<span class="org-keyword">end</span>
</pre>
</div>
</div>
</div>
<div id="outline-container-org03dff09" class="outline-2">
<h2 id="org03dff09">Open Issues</h2>
<div class="outline-text-2" id="text-org03dff09">
<p>
I decided to use 5,000 words after some amount of trial and error. With larger word sets, it takes longer and longer to deserialize the graph. I would like it be able to make use of a broader vocabulary, and I have some ideas for how to make that happen. Although there are probably a variety of ways I could improve the speed of generation of puzzles (multithreading, for instance), I think the best solution is to make it a non-issue by caching previously generated word ladders and reusing them. The reason I haven't done that already basically comes down to the fact that I wanted to get the app up and running, and caching previously generated word ladders introduces some complexity I didn't want to deal with just yet. But that would be the next step.
</p>

<p>
Caching previously generated puzzles opens up a number of possibilities such as:
</p>

<ul class="org-ul">
<li>displaying other user's solutions for the same puzzle</li>
<li>ranking puzzles based on quality/difficulty</li>
<li>Algorithmically determining which puzzle to show the user</li>
<li>Massively broadening the vocabulary of the word set</li>
</ul>

<p>
I have some plans to make the puzzles more conceptually interesting by making them out of conceptually related words rather than just random, but that requires a greater vocabulary first.
</p>

<p>
Another issue is that the leaderboard is too simplistic. It only measures the number of puzzles a user has solved. There's no extra credit for getting a puzzle in fewer steps, solving a puzzler faster, solving a harder puzzle, etc&#x2026;.
</p>
</div>
</div>
]]></description>
</item>
<item>
<title>The Mechanics of Object Oriented JavaScript</title>
<link>http://duncanbritt.com/blog/mechanics-of-oo-js/mechanics-of-oo-js.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/mechanics-of-oo-js/mechanics-of-oo-js.html</guid>
<pubDate>Sun, 14 Nov 2021 00:00:00 -0700</pubDate>
<description><![CDATA[<p>
More than you want to know.
</p>
<div id="outline-container-org790f14c" class="outline-2">
<h2 id="org790f14c">Prerequisites - Execution Context, <code>this</code></h2>
<div class="outline-text-2" id="text-org790f14c">
<p>If you’re not already familiar with execution context in JavaScript, it is a topic worthy of a separate and lengthy article in and of itself. I recommend <a target="_blank" href="https://web.archive.org/web/20180209163541/https://dmitripavlutin.com/gentle-explanation-of-this-in-javascript/">this one.</a> A brief review:</p>

<p>
The execution context of an invocation is what is referenced by the key word <code>this</code> within a function definition. The implicit execution context of an invocation is the receiver- whether an implicit receiver (as in function invocation) or an explicit receiver (as in method invocation).
</p>

<p>
As we shall see, <code>this</code> is useful because it allows programmers to reference the calling object and its properties from within the definition of a method which is shared among many objects.
</p>
</div>
</div>
<div id="outline-container-orgff6bd00" class="outline-2">
<h2 id="orgff6bd00">Functions are objects</h2>
<div class="outline-text-2" id="text-orgff6bd00">
<p>
In Javascript, functions are a type of object. As such, they contain properties like any object can. Every function has a <code>prototype</code> property which, by default, references an object. This prototype object contains a <code>constructor</code> property which, by default, references the function.
</p>


<div id="org9dbee78" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/a.svg" alt="a.svg" class="org-svg" />
</p>
</div>

<p>
To demonstrate this with code, try the following in your browser’s console:
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-keyword">function</span> <span class="org-function-name">aFunction</span>() {
  <span class="org-comment-delimiter">// </span><span class="org-comment">...</span>
}
&#8203;
aFunction.<span class="org-constant">prototype</span>; <span class="org-comment-delimiter">// </span><span class="org-comment">{constructor: &#402;}</span>
aFunction.<span class="org-constant">prototype</span>.constructor === aFunction; <span class="org-comment-delimiter">// </span><span class="org-comment">true  </span>
</pre>
</div>
</div>
</div>
<div id="outline-container-org82974e6" class="outline-2">
<h2 id="org82974e6">Prototypes</h2>
<div class="outline-text-2" id="text-org82974e6">
<p>
In JavaScript, every object has an object prototype referenced by its <code>[[Prototype]</code> property. This property can be accessed by the <code>__proto__</code> accessor method. (It’s pronounced “dunder proto” due to its leading and trailing double underscores). It’s important to note the distinction between a function’s prototype property and the <code>[[Prototype]]</code> property which belongs to all objects (including functions).
</p>

<p>
<i>Before going further, I should mention that accessing an object’s <code>[[Prototype]]</code> directly via the <code>__proto__</code> accessor is deprecated. JavaScript provides the methods Object.getPrototypeOf and Object.setPrototypeOf to access an object’s <code>[[Prototype]]</code>. However, I will continue to use <code>__proto__</code> for explanatory purposes. If you want to test my code in your browser and you find that <code>__proto__</code> doesn’t work, you can substitute <code>foo.__proto__</code> with <code>Object.getPrototypeOf(foo)</code> and it should work.</i>
</p>

<p>
When creating an object via an object literal, its <code>[[Prototype]]</code> property refers to the same object referenced by <code>Object.prototype</code>, which serves as the base <code>[[Prototype]]</code> for all objects. This base prototype object has its own <code>[[Prototype]]</code> property which stores <code>null</code>.
</p>


<div id="orgaf36bc8" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/b.svg" alt="b.svg" class="org-svg" />
</p>
<p><span class="figure-number">Figure 1: </span>Note that <code>Object</code> is a JavaScript function.</p>
</div>

<div class="org-src-container">
<pre class="src src-javascript">( {} ).__proto__ === Object.<span class="org-constant">prototype</span>; <span class="org-comment-delimiter">// </span><span class="org-comment">true;</span>
Object.<span class="org-constant">prototype</span>.__proto__ === <span class="org-constant">null</span>; <span class="org-comment-delimiter">// </span><span class="org-comment">true;  </span>
</pre>
</div>

<p>
Functions being objects, they also have their own <code>[[Prototype]]</code> which I have omitted from the above diagram since its not central to the point of this article. However, for those who are curious, here’s something to chew on:
</p>


<div id="org245291d" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/c.svg" alt="c.svg" class="org-svg" />
</p>
</div>
</div>
</div>
<div id="outline-container-orgc770204" class="outline-2">
<h2 id="orgc770204">Behavior Delegation and the Prototype Chain</h2>
<div class="outline-text-2" id="text-orgc770204">
<p>
The <i>prototype chain</i> of an object refers to the series of objects referenced by each others' <code>[[Prototype]]</code> properties.
</p>


<div id="org42b32a0" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/d.svg" alt="d.svg" class="org-svg" />
</p>
</div>

<p>
A parent is the <code>[[Prototype]]</code> of its child.
When you attempt to access a property of an object, if JavaScript doesn’t find the property within the object, it will search the object’s prototype chain until it either finds the property or reaches the end of the chain, in which case it returns <code>undefined</code>. This is why you can sometimes invoke a method on an object which hasn’t been assigned to a property of that object. All JavaScript objects by default have access to the properties of the object referenced by <code>Object.prototype</code> since it is at the end of their prototype chain.
</p>
<div class="org-src-container">
<pre class="src src-javascript">({}).notAProperty; <span class="org-comment-delimiter">// </span><span class="org-comment">undefined</span>
({}).hasOwnProperty(<span class="org-string">'foo'</span>); <span class="org-comment-delimiter">// </span><span class="org-comment">false</span>
({}).toString(); <span class="org-comment-delimiter">// </span><span class="org-comment">'[object Object]'  &#8203;  </span>
</pre>
</div>

<p>
Type <code>Object.prototype</code> into your browser’s console to view the available methods.
</p>


<div id="org8a9af0b" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/e.svg" alt="e.svg" class="org-svg" />
</p>
</div>

<p>
When an object uses methods which are not assigned to one of its own properties, but are referenced further along the prototype chain, we can call it behavior delegation since the requested invocation is passed along, or delegated, to an object further along the chain. Sometimes this is referred to as prototypal inheritance.
</p>
</div>
</div>
<div id="outline-container-org40261d3" class="outline-2">
<h2 id="org40261d3">Constructor functions</h2>
<div class="outline-text-2" id="text-org40261d3">
<p>
A constructor function is merely a function whose intended purpose is to instantiate objects. Purely by convention, the name of a constructor function is capitalized to distinguish it from other functions. From the perspective of JavaScript, constructor functions are no different from any other functions and are treated the exact same way (despite that the syntax highlighting in your text editor might lead you to believe otherwise).
</p>
</div>
</div>
<div id="outline-container-org666baa5" class="outline-2">
<h2 id="org666baa5">The new keyword</h2>
<div class="outline-text-2" id="text-org666baa5">
<p>
When a function invocation is prefixed with the <code>new</code> keyword, the execution context for the invocation is set to a new object, sometimes referred to as an instance, which is returned by the expression. (Note: It is only returned by the expression if an object isn’t explicitly returned within the function definition.) Therefore, within the definition of a constructor function, <code>this</code> can be used to assign instance properties to values. If you forget to use <code>new</code> when invoking your constructor function, you’ll assign values to properties of the global object. Don’t do that.
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-keyword">function</span> <span class="org-function-name">Constructor</span>(<span class="org-variable-name">val</span>) {
  <span class="org-constant">this</span>.foo = val;
}
&#8203;
<span class="org-keyword">const</span> <span class="org-variable-name">instance</span> = <span class="org-keyword">new</span> <span class="org-type">Constructor</span>(<span class="org-string">'bar'</span>);
instance.__proto__ === Constructor.<span class="org-constant">prototype</span>; <span class="org-comment-delimiter">// </span><span class="org-comment">true</span>
&#8203;
<span class="org-keyword">const</span> <span class="org-variable-name">instance2</span> = <span class="org-keyword">new</span> <span class="org-type">Constructor</span>(<span class="org-string">'baz'</span>);
instatnce2.__proto__ === Constructor.<span class="org-constant">prototype</span>; <span class="org-comment-delimiter">// </span><span class="org-comment">true</span>
&#8203;
instance.foo; <span class="org-comment-delimiter">// </span><span class="org-comment">'bar'</span>
instance2.foo; <span class="org-comment-delimiter">// </span><span class="org-comment">'baz'</span>
</pre>
</div>


<div id="orgfcca519" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/f.svg" alt="f.svg" class="org-svg" />
</p>
</div>

<p>
Notice that the <code>[[Prototype]]</code> of the instances is the same object referenced by <code>Constructor.prototype</code>. We can define functions as properties of the prototype to create shared methods accessible to all instances.
</p>

<div class="org-src-container">
<pre class="src src-javascript">Constructor.<span class="org-constant">prototype</span>.xyz = <span class="org-keyword">function</span>() {
  <span class="org-keyword">return</span> <span class="org-constant">this</span>;
}
&#8203;
instance.xyz();                 <span class="org-comment-delimiter">//  </span><span class="org-comment">{foo: 'bar'}</span>
instance2.xyz();                <span class="org-comment-delimiter">//  </span><span class="org-comment">{foo: 'baz'}</span>
instance.hasOwnProperty(<span class="org-string">'xyz'</span>); <span class="org-comment-delimiter">// </span><span class="org-comment">false;</span>
</pre>
</div>


<div id="orgadc7102" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/g.svg" alt="g.svg" class="org-svg" />
</p>
</div>
</div>
</div>
<div id="outline-container-org903754c" class="outline-2">
<h2 id="org903754c">Inheritance</h2>
<div class="outline-text-2" id="text-org903754c">
<p>
Supposing we want to create a subtype of object that inherits from <code>Constructor</code>. Our first naive attempt might look something like this:
</p>
<div class="org-src-container">
<pre class="src src-javascript"><span class="org-comment-delimiter">// </span><span class="org-comment">bad</span>
<span class="org-keyword">function</span> <span class="org-function-name">ChildConstructor</span>(<span class="org-variable-name">val</span>, <span class="org-variable-name">ownValue</span>) {
  Constructor.call(<span class="org-constant">this</span>, val);
  <span class="org-constant">this</span>.qux = ownValue;
}
&#8203;
<span class="org-keyword">const</span> <span class="org-variable-name">childInstance</span> = <span class="org-keyword">new</span> <span class="org-type">ChildConstructor</span>(<span class="org-string">'xyzzy'</span>, 5);
&#8203;
childInstance.xyz(); <span class="org-comment-delimiter">// </span><span class="org-comment">Uncaught TypeError:</span>
<span class="org-comment-delimiter">// </span><span class="org-comment">childInstance.xyz is not a function  </span>
</pre>
</div>

<p>
The problem with this is that the <code>[[Prototype]]</code> property of <code>ChildConstructor.prototype</code> points to <code>Object.prototype</code>.
</p>

<div class="org-src-container">
<pre class="src src-javascript">childConstructor.<span class="org-constant">prototype</span>.__proto__ === Object.<span class="org-constant">prototype</span>;
<span class="org-comment-delimiter">// </span><span class="org-comment">true  </span>
</pre>
</div>

<div style="background: var(--svg-bg)">

<div id="org2affb12" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/h.svg" alt="h.svg" class="org-svg" />
</p>
</div>
</div>

<p>
Therefore, no property by the name of <code>xyz</code> can be found on the child instance’s prototype chain. In order to have access to <code>xyz</code>, we need to put <code>Constructor.prototype</code> on the child instance’s prototype chain by setting <code>ChildConstructor.prototype~’s ~[[Prototype]]</code> to be <code>Constructor.prototype</code>. What a mouthful! Our next naive attempt might look something like this:
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-comment-delimiter">// </span><span class="org-comment">less bad</span>
<span class="org-keyword">function</span> <span class="org-function-name">ChildConstructor</span>(<span class="org-variable-name">val</span>, <span class="org-variable-name">ownValue</span>) {
  Constructor.call(<span class="org-constant">this</span>, val);
  <span class="org-constant">this</span>.qux = ownValue;
}
&#8203;
ChildConstructor.<span class="org-constant">prototype</span>.__proto__ = Constructor.<span class="org-constant">prototype</span>;
&#8203;
<span class="org-keyword">const</span> <span class="org-variable-name">childInstance</span> = <span class="org-keyword">new</span> <span class="org-type">ChildConstructor</span>(<span class="org-string">'xyzzy'</span>, 5);
&#8203;
childInstance.xyz(); <span class="org-comment-delimiter">// </span><span class="org-comment">{foo: 'xyzzy', qux: 5}</span>
</pre>
</div>

<p>This works, however, it is recommended that you avoid altering the <code class="src src-javascript">[[Prototype]]</code> of an object for performance reasons. 
<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf">This article</a> on MDN offers a better explanation. Alternatively, you can reassign the child constructor’s prototype property to a new object whose <code class="src src-javascript">[[Prototype]]</code> is already the desired object, using <code class="src src-javascript">Object.create</code>.</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-comment-delimiter">// </span><span class="org-comment">not bad</span>
<span class="org-keyword">function</span> <span class="org-function-name">ChildConstructor</span>(<span class="org-variable-name">val</span>, <span class="org-variable-name">ownValue</span>) {
  Constructor.call(<span class="org-constant">this</span>, val);
  <span class="org-constant">this</span>.qux = ownValue;
}
&#8203;
ChildConstructor.<span class="org-constant">prototype</span> = Object.create(Constructor.<span class="org-constant">prototype</span>);
ChildConstructor.<span class="org-constant">prototype</span>.constructor = ChildConstructor;
&#8203;
ChildConstructor.<span class="org-constant">prototype</span>.childFunction = <span class="org-keyword">function</span>() {
  <span class="org-keyword">return</span> <span class="org-constant">this</span>.foo;
}
&#8203;
<span class="org-keyword">const</span> <span class="org-variable-name">childInstance</span> = <span class="org-keyword">new</span> <span class="org-type">ChildConstructor</span>(<span class="org-string">'xyzzy'</span>, 5);
&#8203;
childInstance.xyz();                                    
<span class="org-comment-delimiter">// </span><span class="org-comment">{foo: 'xyzzy', qux: 5}</span>
childInstance.childFunction();                          
<span class="org-comment-delimiter">// </span><span class="org-comment">'xyzzzy';</span>
childInstance.qux;                                      
<span class="org-comment-delimiter">// </span><span class="org-comment">5</span>
childInstance.__proto__ === ChildConstructor.<span class="org-constant">prototype</span>;
<span class="org-comment-delimiter">// </span><span class="org-comment">true</span>
childInstance.constructor === ChildConstructor;         
<span class="org-comment-delimiter">// </span><span class="org-comment">true</span>
</pre>
</div>

<p>
<code>Object.create</code>, when called, creates and returns a new object whose <code>[[Prototype]]</code> is the argument to the invocation of <code>Object.create</code>. But this new object doesn’t have its own constructor property. Notice that we assign <code>ChildConstructor</code> to <code>ChildConstructor.prototype.constructor</code>. Otherwise the expression <code>childInstance.constructor</code> would return <code>Constructor</code> instead of <code>ChildConstructor</code>.
</p>


<div style="background: var(--svg-bg)">

<div id="orgbcc5ac4" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/i.svg" alt="i.svg" class="org-svg" />
</p>
</div>
</div>
</div>
</div>
<div id="outline-container-org2b0f81e" class="outline-2">
<h2 id="org2b0f81e">Objects Linking to Other Objects (OLOO)</h2>
<div class="outline-text-2" id="text-org2b0f81e">
<p>
To quickly build a mental model of the OLOO pattern of object creation, compare the above diagram to the following:
</p>

<div style="background: var(--svg-bg)">

<div id="org6d99fd2" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/j.svg" alt="j.svg" class="org-svg" />
</p>
</div>
</div>

<p>
The purpose of <code>Object.create</code> is worth reiterating:
</p>

<p>
<code>Object.create</code>, when called, creates and returns a new object whose <code>[[Prototype]]</code> is the argument to the invocation of <code>Object.create</code>.
</p>

<p>
We can use an object literal to create a prototype. Then we’ll use <code>Object.create</code> to make objects which link to that object. We can use an initializer method to set the values of instance properties on our newly created object.
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-keyword">const</span> <span class="org-variable-name">Prototype</span> = {
  <span class="org-function-name">addA</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">n</span>) {
    <span class="org-keyword">return</span> <span class="org-constant">this</span>.a + n;
  }
  &#8203;
  <span class="org-function-name">init</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">n</span>) {
    <span class="org-constant">this</span>.a = a;
    <span class="org-keyword">return</span> <span class="org-constant">this</span>;
  }
}
&#8203;
<span class="org-keyword">const</span> <span class="org-variable-name">instance</span> = Object.create(Prototype).init(20);
&#8203;
instance.a;                       <span class="org-comment-delimiter">// </span><span class="org-comment">20</span>
instance.addA(10);                <span class="org-comment-delimiter">// </span><span class="org-comment">30</span>
instance.__proto__ === Prototype; <span class="org-comment-delimiter">// </span><span class="org-comment">true  &#8203;  </span>
</pre>
</div>

<div style="background: var(--svg-bg)">

<div id="orge803829" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/k.svg" alt="k.svg" class="org-svg" />
</p>
</div>
</div>

<p>
The process for making a subtype is fairly straightforward.
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-keyword">const</span> <span class="org-variable-name">ChildPrototype</span> = Object.create(Prototype);
ChildPrototype.init = <span class="org-keyword">function</span>(<span class="org-variable-name">a</span>, <span class="org-variable-name">b</span>) {
  Prototype.init(<span class="org-constant">this</span>, a);
  <span class="org-constant">this</span>.b = b;
  <span class="org-keyword">return</span> <span class="org-constant">this</span>;
};
&#8203;
<span class="org-keyword">const</span> <span class="org-variable-name">childInstance</span> = Object.create(ChildPrototype).init(5, 7);
childInstance;         <span class="org-comment-delimiter">// </span><span class="org-comment">{a: 5, b: 7}</span>
childInstance.addA(3); <span class="org-comment-delimiter">// </span><span class="org-comment">8</span>
childInstance.__proto__ === ChildPrototype; <span class="org-comment-delimiter">// </span><span class="org-comment">true</span>
childInstance.hasOwnPrototype(<span class="org-string">'addA'</span>);      <span class="org-comment-delimiter">// </span><span class="org-comment">false  </span>
</pre>
</div>

<div style="background: var(--svg-bg)">

<div id="org389c249" class="figure">
<p><img src="http://duncanbritt.com/blog/mechanics-of-oo-js/images/l.svg" alt="l.svg" class="org-svg" />
</p>
</div>
</div>
</div>
</div>
]]></description>
</item>
<item>
<title>JavaScript Execution Context</title>
<link>http://duncanbritt.com/blog/javascript-execution-context/javascript-execution-context.html</link>
<guid isPermaLink="true">http://duncanbritt.com/blog/javascript-execution-context/javascript-execution-context.html</guid>
<pubDate>Fri, 05 Nov 2021 00:00:00 -0600</pubDate>
<description><![CDATA[<div id="outline-container-org60dcf9e" class="outline-2">
<h2 id="org60dcf9e">Why <code>this</code>?</h2>
<div class="outline-text-2" id="text-org60dcf9e">
<p>
Suppose you want to reference the calling object within a method definition. This can be achieved using the keyword <code>this</code>. It sounds simple, but there are some crucial details which may be unintuitive for the uninitiated. We’ll start by exploring the fact that JavaScript has first class functions. This means that functions may be assigned to a variable, passed as an argument, or returned by a function invocation. To understand the implications with regards to `this`, let’s take a brief detour and talk about methods.
</p>
</div>
</div>
<div id="outline-container-org62cf631" class="outline-2">
<h2 id="org62cf631">Methods in JavaScript</h2>
<div class="outline-text-2" id="text-org62cf631">
<p>
In a class-based Object Oriented language, we might think of (instance) methods as functions which are defined by a class and are associated with/accessible to instances of the class. This definition is problematic in JavaScript for two reasons.
</p>

<ol class="org-ol">
<li>Despite the class syntax introduced in ES6, JavaScript doesn’t have true classes.</li>

<li>JavaScript functions are first class.</li>
</ol>

<p>
Let’s focus on the second point. When a function is assigned to a property of an object, we can call it one of the object’s methods. But the same function which is assigned to a property of an object may also be assigned to a variable, or another object’s property.
</p>

<div class="org-src-container">
<pre class="src src-javascript"><span class="org-keyword">const</span> <span class="org-variable-name">foo</span> = <span class="org-keyword">function</span>() {
  console.log(<span class="org-string">'Hello, World!'</span>);
}

<span class="org-keyword">const</span> <span class="org-variable-name">object</span> = { bar: foo };

foo();        <span class="org-comment-delimiter">// </span><span class="org-comment">prints Hello, World!</span>
object.bar(); <span class="org-comment-delimiter">// </span><span class="org-comment">prints Hello, World!</span>
</pre>
</div>


<div id="orgacc200f" class="figure">
<p><img src="http://duncanbritt.com/blog/javascript-execution-context/images/1.svg" alt="1.svg" class="org-svg" />
</p>
</div>

<p>
Rather than thinking in terms of functions vs methods, in JavaScript, it makes more sense to think in terms of <i>function invocation</i> — via <code>foo();</code> vs <i>method invocation</i> — à la <code>object.bar()</code>. Method invocation in JavaScript is when a function is called on an object. Another way of saying this is that it is invoked with an <i>explicit receiver</i> — whereas function invocation is when a function is invoked with an <i>implicit receiver</i>. The implicit receiver of a (function) invocation is the global object. In a browser, this is the <code>window</code> object.
</p>

<p>
Normally, within a function/method definition, <code>this</code> references the receiver of an invocation thereof. Even so, the consequences might seem strange. Consider the following code snippet:
</p>

<div class="org-src-container">
<pre class="src src-js"><span class="org-keyword">const</span> <span class="org-variable-name">doubler</span> = {
  multiplier: 2,

  <span class="org-function-name">double</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">n</span>) {
    <span class="org-keyword">return</span> n * <span class="org-constant">this</span>.multiplier; <span class="org-comment-delimiter">// </span><span class="org-comment">n * undefined =&gt; NaN</span>
  },

  <span class="org-function-name">doubleAll</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">numbers</span>) {
    <span class="org-keyword">return</span> numbers.map(<span class="org-constant">this</span>.<span class="org-type">double</span>);
  },
};

doubler.doubleAll([1, 2, 3]); <span class="org-comment-delimiter">// </span><span class="org-comment">returns [NaN, NaN, NaN]</span>
</pre>
</div>

<p>
It might be tempting to think the code should return <code>[2, 4, 6]</code>. The trouble is that within the body of <code>map</code> our <code>double</code> function is referenced by a parameter and is invoked with an implicit receiver. To illustrate this, imagine that JavaScript’s <code>Array.prototype.map</code>  method is implemented thusly:
</p>

<div class="org-src-container">
<pre class="src src-js">Array.<span class="org-constant">prototype</span>.map = <span class="org-keyword">function</span>(<span class="org-variable-name">funcParam</span>) {
  newArray = [];

  <span class="org-constant">this</span>.forEach(item =&gt; {
    newArray.push(funcParam(item)); <span class="org-comment-delimiter">// </span><span class="org-comment">function invocation</span>
  });               <span class="org-comment-delimiter">// </span><span class="org-comment">^^^ funcParam invoked with an implicit receiver</span>

  <span class="org-keyword">return</span> newArray;
};
</pre>
</div>

<p>
It is irrelevant that <code>double</code> is a property of the <code>doubler</code> object. It’s not where the function is defined that determines its <i><code>this</code> binding</i>, but rather, the context in which it is invoked. The term <b>implicit execution context</b> is used to refer to the receiver of an invocation.
</p>

<ul class="org-ul">
<li><code>this</code> references the execution context of a function/method invocation.</li>

<li>The implicit execution context of an invocation is the receiver, whether explicit (as in method invocation) or implicit (as in function invocation).</li>
</ul>
</div>
</div>
<div id="outline-container-org8cc118b" class="outline-2">
<h2 id="org8cc118b">Context Loss</h2>
<div class="outline-text-2" id="text-org8cc118b">
<p>
In the last example, the fact that <code>this</code> within <code>double</code> doesn’t reference <code>doubler</code> when invoked is called context loss. There are a variety of strategies to deal with context loss. 
</p>
</div>
</div>
<div id="outline-container-orgc82ba64" class="outline-2">
<h2 id="orgc82ba64"><code>this</code> Argument</h2>
<div class="outline-text-2" id="text-orgc82ba64">
<p>
Conveniently, many of JavaScript’s built array methods allow you to pass in an object which will serve as the execution context for the function which is passed in. Using this strategy in our previous example would look like this: 
</p>

<div class="org-src-container">
<pre class="src src-js"><span class="org-keyword">const</span> <span class="org-variable-name">doubler</span> = {
  multiplier: 2,

  <span class="org-function-name">double</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">n</span>) {
    <span class="org-keyword">return</span> n * <span class="org-constant">this</span>.multiplier;
  },

  <span class="org-function-name">doubleAll</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">numbers</span>) {
    <span class="org-keyword">return</span> numbers.map(<span class="org-constant">this</span>.<span class="org-type">double</span>, <span class="org-constant">this</span>); <span class="org-comment-delimiter">// </span><span class="org-comment">&lt;- this argument</span>
  },
};

doubler.doubleAll([1, 2, 3]); <span class="org-comment-delimiter">// </span><span class="org-comment">returns [2, 4, 6]</span>
</pre>
</div>
</div>
</div>
<div id="outline-container-orga94dbbe" class="outline-2">
<h2 id="orga94dbbe">Arrow Functions</h2>
<div class="outline-text-2" id="text-orga94dbbe">
<p>
Alternatively, we could wrap the double function in an arrow function. This works because, unlike other JavaScript functions, the this binding of an arrow function is determined lexically, on the basis of where it is defined, not how it is invoked.
</p>

<div class="org-src-container">
<pre class="src src-js"><span class="org-keyword">const</span> <span class="org-variable-name">doubler</span> = {
    multiplier: 2,

    <span class="org-function-name">double</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">n</span>) {
        <span class="org-keyword">return</span> n * <span class="org-constant">this</span>.multiplier;
    },

    <span class="org-function-name">doubleAll</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">numbers</span>) {
        <span class="org-keyword">return</span> numbers.map(n =&gt; <span class="org-constant">this</span>.<span class="org-type">double</span>(n)); <span class="org-comment-delimiter">// </span><span class="org-comment">&lt;- arrow function</span>
    },
};

doubler.doubleAll([1, 2, 3]); <span class="org-comment-delimiter">// </span><span class="org-comment">returns [2, 4, 6]</span>
</pre>
</div>

<p>
Since our arrow function is defined within the body of <code>doubleAll</code>, <code>this</code> within the arrow function references the execution context of the invocation of <code>doubleAll</code>.
</p>
</div>
</div>
<div id="outline-container-org14215e1" class="outline-2">
<h2 id="org14215e1">Variable Assignment - self</h2>
<div class="outline-text-2" id="text-org14215e1">
<p>
Another idiom for dealing with context loss is to assign `this` to a local variable, such as `self`, and replace `this` with `self` within the callback function.
</p>

<div class="org-src-container">
<pre class="src src-js"><span class="org-keyword">const</span> <span class="org-variable-name">doubler</span> = {
  multiplier: 2,

  <span class="org-function-name">double</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">n</span>) {
    <span class="org-keyword">return</span> n * <span class="org-constant">this</span>.multiplier;
  },

  <span class="org-function-name">doubleAll</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">numbers</span>) {
    <span class="org-keyword">const</span> <span class="org-variable-name">self</span> = <span class="org-constant">this</span>;
    <span class="org-keyword">return</span> numbers.map(<span class="org-keyword">function</span>(<span class="org-variable-name">n</span>) {
      <span class="org-keyword">return</span> self.<span class="org-type">double</span>(n);
    });
  },
};

doubler.doubleAll([1, 2, 3]); <span class="org-comment-delimiter">// </span><span class="org-comment">returns [2, 4, 6]</span>
</pre>
</div>

<p>
This works because the object referenced by <code>self</code> is not context dependent. <code>self</code> is simply a local variable, forever accessible to nested functions via closure.
</p>
</div>
</div>
<div id="outline-container-org460886a" class="outline-2">
<h2 id="org460886a"><code>bind</code></h2>
<div class="outline-text-2" id="text-org460886a">
<p>
We could use the <code>bind</code> method to return a new function whose execution context is permanently and irreversibly hard bound to the first argument of bind.
</p>

<div class="org-src-container">
<pre class="src src-js"><span class="org-keyword">const</span> <span class="org-variable-name">doubler</span> = {
  multiplier: 2,

  <span class="org-function-name">double</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">n</span>) {
    <span class="org-keyword">return</span> n * <span class="org-constant">this</span>.multiplier;
  },

  <span class="org-function-name">doubleAll</span>: <span class="org-keyword">function</span>(<span class="org-variable-name">numbers</span>) {
    <span class="org-keyword">const</span> <span class="org-variable-name">self</span> = <span class="org-constant">this</span>;
    <span class="org-keyword">return</span> numbers.map(<span class="org-constant">this</span>.<span class="org-type">double</span>.bind(<span class="org-constant">this</span>));
  },
};

doubler.doubleAll([1, 2, 3]); <span class="org-comment-delimiter">// </span><span class="org-comment">returns [2, 4, 6]</span>
</pre>
</div>
</div>
</div>
<div id="outline-container-org1ec166d" class="outline-2">
<h2 id="org1ec166d"><code>call</code> &amp; <code>apply</code></h2>
<div class="outline-text-2" id="text-org1ec166d">
<p>
This example problem doesn’t lend itself to the final idiom for dealing with context loss that I will show you, so I’ll offer a different example. The <code>call</code> and <code>apply</code> methods can each be used to to invoke a function with its execution context set to the first argument to the invocation thereof. Behold:
</p>

<div class="org-src-container">
<pre class="src src-js"><span class="org-keyword">function</span> <span class="org-function-name">xyzzy</span>() {
  <span class="org-keyword">return</span> <span class="org-constant">this</span>.a;
}

foo = { a: 5 };

xyzzy.call(foo); <span class="org-comment-delimiter">// </span><span class="org-comment">returns 5</span>
</pre>
</div>
</div>
</div>
]]></description>
</item>
</channel>
</rss>
