<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jed Schneider on Medium]]></title>
        <description><![CDATA[Stories by Jed Schneider on Medium]]></description>
        <link>https://medium.com/@jedschneider?source=rss-5cbfadff4e79------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*goQEwUddZHf-53Oa.jpeg</url>
            <title>Stories by Jed Schneider on Medium</title>
            <link>https://medium.com/@jedschneider?source=rss-5cbfadff4e79------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 15:00:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jedschneider/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Laptop Local: A DevOps Oriented Workflow for Mac OS (X)]]></title>
            <link>https://jedschneider.medium.com/laptop-local-a-devops-oriented-workflow-for-mac-os-x-ecc67c6badf?source=rss-5cbfadff4e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecc67c6badf</guid>
            <category><![CDATA[configuration-management]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[mac]]></category>
            <category><![CDATA[system-administration]]></category>
            <dc:creator><![CDATA[Jed Schneider]]></dc:creator>
            <pubDate>Wed, 27 Jun 2018 15:55:48 GMT</pubDate>
            <atom:updated>2018-06-27T15:55:48.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwtJunch5xkDNRuko3b84w.jpeg" /><figcaption>Baby Edward: ready for configuration management.</figcaption></figure><p>I’ve had the same laptop now since 2015, and after 3 years, its become a bit full of things. Old client things, old me things, millions of lines of development logs. I also wanted to experiment with zsh as my shell and revamp my vim setup, so it seemed like a good time to nuke my hard drive and start fresh. Coming off some time as a devops engineer, I also decided that I wanted to think a little differently about how I setup development dependencies like linux utilities, installed GUI programs, frameworks, and other dev tools. That is: treat my laptop with the same kind of idempotence and repeatability that I’d treat the web servers that run my applications. <a href="https://github.com/jedschneider/laptop-local">Laptop Local</a> is my current solution. Below are descriptions of the core tools I am using to support this process. My core objective is to have no files or dependencies on my local laptop that exist undefined at some level in code, and no local files that are not replaceable by cloud copies. <a href="https://www.apple.com/macos/mojave-preview/">Mojave</a> is coming, and I’ll be ready! Every new install will be a wipe and replace. At some point I’d like to be in a situation where I can pickup any laptop and with three things, be ready to work:</p><p>1) A clean install of OS X</p><p>2) My Apple ID login</p><p>3) Another device configured on my <a href="https://medium.com/keybase.io">Keybase</a> account (iPhone, eg)</p><p>Following is a list of core tools required to support the workflow.</p><h4>Laptop</h4><p>After recently visiting and working with the folks at <a href="https://medium.com/thoughtbot.com">Thoughtbot</a>, I was once again invigorated by Vim and willing to try the <a href="https://medium.com/github.com/thoughtbot/dotfiles">dotset</a> that they maintain in replacement of Intellij Ultimate, which I’ve quite enjoyed over the last 4 or so years. While reading the README I realized they had an extensible install script (<a href="https://github.com/thoughtbot/laptop">laptop</a>) that setup most of the core dependencies I wanted for development.</p><h4>Homebrew</h4><p>I’ve used <a href="https://medium.com/brew.sh">homebrew</a> extensively in the past to install local versions of core packaged command line utilities. Things like git, imagemagick, Postgres, redis, etc. I was also aware of brew-cask but had not used it too extensively. Most notably, I always just installed these dependencies on the fly. If I realized I didn’t have imagemagick installed, I’d just hop onto the command line and run brew install imagemagick but, I never really kept track of what I added, which meant moving to a new machine provided a certain level of unpredictability.</p><p>It also meant that if I encountered strange issues, it was less clear where those issues might have originated.</p><h4>Cask</h4><p><a href="https://caskroom.github.io/">Cask</a> is an extension of homebrew used for managing installation of software that homebrew considers “outside” core. These are typically things like downloadable dmgs for GUI type applications. Casks follow a very similar DSL for defining the install process but thus far, I have not had to publish my own, as all the software I’ve needed has been available. Cask provides a search mechanism via the cli: brew cask search &lt;term&gt;, but I’ve had the most luck doing a google search for “cask &lt;application&gt;”.</p><h4>MAS</h4><p>New on my radar is the Mac App Store cli, or <a href="https://github.com/mas-cli/mas">“mas”</a> for short. The process is a little awkward in that you need to find the unique identifier of the application in order to install, but it is a small price to pay for managing app store applications in a declarative and repeatable process.</p><h4>Bash</h4><p>I’ve seen a few other folks using tools like <a href="https://www.ansible.com/">Ansible</a> to manage configuration on their macs, and this might be a direction I go in the future (though I’d probably use <a href="https://www.chef.io/">Chef</a>) but I like being able to bootstrap the process with Bash as the only core dependency. There are certainly some major advantages to using a higher abstraction tool, like built in mechanisms to handle configuration secrets, but it does add a level of complexity and it is uncertain you could cover all edge cases for personalization of application installs (like adding a license key) without UI automation. For now, I’m OK with doing the final configuration by hand.</p><h4>Managing Dependencies with Version Control</h4><p>By moving my process to a version controlled process, I can better track what things I’ve added, when, and what, might have changed when a problem arises. I use <a href="https://medium.com/git-scm.org">git</a> and store my repository on <a href="https://medium.com/github.com/jedschneider">Github</a>.</p><h3>A unified process</h3><p>Most importantly, I have a workflow that unifies how I added software to my computer. Before, I had to remember if I had installed TaskBadges through the Mac App Store or through Cask and I had a multitude of entry points to the process of adding software to my environment. I then had a separate process for configuration of these dependencies, and a final process for managing my development environment, aka dotfiles. Now, the entry point is the same for all changes to my laptop.</p><h4>How it works</h4><p>The following is an animated gif showing the installation of the tree dependency with homebrew.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*5yOD2TmpptYFW8-7IohebQ.gif" /></figure><p>Instead of just installing directly with brew install tree, I open up my editor, modify an inline brewfile in my laptop-local script, and then run the laptop/mac script which runs the core installs, and then picks up my customizations and runs those. The script detects a new dependency and installs it. Now I can commit this change to source control and it will be automatically installed in the future when I reinstall. Laptop also keeps this file updated with the most current release of tree.</p><p>The script is organized into three core segments:</p><p>1) An inline brewfile with any cask installed dependencies, followed by any brew installed dependencies.</p><pre>brew bundle --file=- &lt;&lt;EOF<br>  cask &quot;1password&quot;<br>  cask &quot;acslogo&quot;<br>  cask &quot;encryptr&quot;<br>  cask &quot;google-chrome&quot;<br>  cask &quot;imageoptim&quot;<br>  cask &quot;iterm2&quot;<br>  cask &quot;keybase&quot;<br>  cask &quot;rescuetime&quot;<br>  cask &quot;semaphor&quot;<br>  cask &quot;todotxt&quot;<br>  cask &quot;zwift&quot;<br><br>  # fonts<br>  tap &quot;caskroom/fonts&quot;<br>  cask &quot;font-fira-code&quot;<br>  cask &quot;font-source-code-pro&quot;<br><br>  # for dotfiles<br>  tap &quot;thoughtbot/formulae&quot;<br>  brew &quot;rcm&quot;<br><br>  brew &quot;mas&quot; # Apple App Store integration<br><br>  brew &quot;hugo&quot;<br><br>  brew &quot;go&quot;<br>  brew &quot;terraform&quot;<br><br>  brew &quot;ttygif&quot;<br>  brew &quot;imageoptim-cli&quot;<br><br>EOF</pre><p>2) Apple Store Installed Dependencies</p><pre># install Apps From App Store<br>mas install 568494494 # Pocket<br>mas install 1225570693 # Ulysses<br>mas install 1055511498 # Day One<br>mas install 1142578753 # Omnigraffle 7<br>mas install 803453959 # slack<br>mas install 454948164 #TaskBadges<br><br># upgrade existing apps<br>mas upgrade</pre><p>3) Any custom gems (for ruby development) not included by Laptop core, note I’m calling out to a pre existing bash function defined by Laptop core. Because it runs before, its scoped.</p><pre># gems<br>gem_install_or_update &quot;middleman&quot;<br>gem_install_or_update &quot;middleman-blog&quot;</pre><p>4) Dotfile installation. Note: I have a dotfiles-local as well that provides customization to my dotfiles for my text editor and cli environments.</p><pre># bring in or pull from Thoughtbot&#39;s dotfiles<br>if [ ! -d &quot;$HOME/dotfiles&quot; ]; then<br>  git clone git://github.com/thoughtbot/dotfiles.git ~/dotfiles<br>else<br>  git -C ~/dotfiles pull origin master<br>fi<br><br># source dotfiles<br>env RCRC=$HOME/dotfiles/rcrc rcup</pre><h4>Outro</h4><p>Thanks for reading! I hope this helps open up some ideas for your own laptop management. I’m really excited about some of the newer options in this space like MAS and the growth of Cask.</p><p>A special thanks to <a href="https://github.com/thoughtbot">Thoughtbot</a> for their extensive open source work so that I can focus on “building on the shoulders of giant robots”. 🍻</p><p>Applause, shares, and follows are welcomed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecc67c6badf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Domain Oriented Thinking]]></title>
            <link>https://jedschneider.medium.com/domain-oriented-thinking-7923c13c2328?source=rss-5cbfadff4e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/7923c13c2328</guid>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Jed Schneider]]></dc:creator>
            <pubDate>Fri, 20 Oct 2017 19:53:49 GMT</pubDate>
            <atom:updated>2017-10-20T19:53:49.920Z</atom:updated>
            <content:encoded><![CDATA[<p>In my mind, the difference between domain thinking and discrete problem thinking is how considerate you are of others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IxpmDudldG_PpY2_MCWbOA.png" /><figcaption>A rose from our garden. At some level its all about strands of DNA and individual nucleic acids. But I just like the color.</figcaption></figure><blockquote>Even if you don’t intend anybody else to read your code, there’s still a very good chance that somebody will have to stare at your code and figure out what it does: That person is probably going to be you, twelve months from now. — <a href="https://blogs.msdn.microsoft.com/oldnewthing/20070406-00/?p=27343">Raymond Chen</a></blockquote><h4>Who is the downstream customer of the code you write?</h4><p>Usually, that downstream customer is you. If it isn’t, its one of your friends or colleagues, or the person that might be cursing your name for the code you left them to decipher.</p><p>When that downstream customer is you, you’re likely on the phone with one of your clients trying to align the process they are describing with the one that you have encoded. In that moment, its often really nice to have a 1:1 mapping between the grammar they are using in their domain, and the way that you have described the execution of the code in your source code.</p><h4>A discrete solution approach</h4><p>I have been working with some of our University interns doing some extra-curriculum work learning programming languages. Currently we are learning Ruby by doing a combination of book work and problem solving on the <a href="https://exercism.io/">exercism.io</a> platform. One of the first problems to be solved in the Ruby track is the <a href="http://exercism.io/exercises/ruby/hamming/readme">Hamming distance problem</a>. That is to say the difference in character placement between two strings of identical length. A discrete problem based approach might look like this:</p><pre>class Hamming<br>  def self.compute(strand1, strand2)<br>    raise ArgumentError.new unless strand1.length == strand2.length<br>    s1, s2 = [strand1, strand2].map { |x| x.split(//)}<br>    s1.zip(s2).count {|(a,b)| a != b }<br>  end<br>end</pre><p>I challenged my students to think about talking through this code with a subject matter expert facing the problem and how much they would have to translate primitives and mechanics of the language in that conversation. Because we are using base types in the language, we must model our problem more directly around those types rather than the grammar that describes the domain.</p><h4>Towards domain thinking</h4><p>Domain based problem solving focuses more on outcome and future state than the immediate resolution. Clearly there is also a danger to ‘over-engineer’ for the future and pre-load the solution with too much future proofing.</p><p>Returning to Ruby after some time away, I am yet again happy with the tools available within the language to produce a reasonable representation that models your domain, without the ceremony required for normal object composition.</p><h4>Specification: A Point Mutation is difference between to Nucleotides in the same position within a strand:</h4><pre>class Nucleotide &lt; SimpleDelegator<br>  alias :point_mutation? :!=<br>end<br><br>Nucleotide.new(&quot;A&quot;).point_mutation?(Nucelotide.new(&quot;B&quot;)) =&gt; true</pre><p>We accomplish this abstraction by using the SimpleDelegator class to delegate all messages to the object passed into the constructor. In the example use case &quot;A&quot; and &quot;B&quot; are used as the delegate objects. alias delegates the message passed to point_mutation? to the != method, which in turn delegates this to the delegate object. We can then use this base class in the next level of our abstraction.</p><h4>Specification: A strand of DNA is made up of an ordered series of Nucleotides</h4><pre>class Strand &lt; SimpleDelegator<br>  def self.parse(str)<br>    arr = str.split(&quot;&quot;)<br>    new(arr.map {|x| Nucleotide.new(x)})<br>  end<br>end<br><br>Strand.parse(&quot;AA&quot;).inspect # =&gt; =&gt; &quot;[\&quot;A\&quot;, \&quot;A\&quot;]&quot;<br>Strand.parse(&quot;AA&quot;).class # =&gt; Strand<br>Strand.parse(&quot;AA&quot;)[0].class # =&gt; Nucleotide</pre><p>Again, we use SimpleDelegator to decorate the Array passed to the constructor in parse. And so doing, we can now decorate the base data structure with our own implementation needs, and allows us to continue with the next specification.</p><h4>Specification: hamming difference is the total difference between strands of a similar length.</h4><pre>class Strand &lt; SimpleDelegator<br>  def self.parse(str)<br>    arr = str.split(&quot;&quot;)<br>    new(arr.map {|x| Nucleotide.new(x)})<br>  end<br><br>  def same_length?(other)<br>    self.length == other.length<br>  end<br><br>  def -(other)<br>    self.zip(other).count{|(a,b)| a.point_mutation?(b) }<br>  end<br><br>  alias :hamming_distance :-<br>end<br><br>Strand.parse(&quot;A&quot;).same_length?(Strand.parse(&quot;B&quot;)) # =&gt; true<br>Strand.parse(&quot;A&quot;) - Strand.parse(&quot;B&quot;) # =&gt; 1<br>Strand.parse(&quot;A&quot;).hamming_difference(Strand.parse(&quot;B&quot;)) # =&gt; 1</pre><p>As shown in the example above, we have two ways to describe difference, both mathematically oriented, with — , and also with a named method. We can now implement our Hamming.compute solution using a more domain oriented grammar.</p><pre>class Hamming<br>  def self.compute(str1, str2)<br>    strand1 = Strand.parse(str1)<br>    strand2 = Strand.parse(str2)</pre><pre>    raise ArgumentError.new unless strand1.same_length?(strand2)</pre><pre>    strand1.hamming_distance(strand2)<br>    # alternatively <br>    # strand1 - strand2<br>  end<br>end</pre><p>And, at least I believe, it would be easier to have a meaningful conversation over the phone with my biologist subject matter expert.</p><p>“Yes, the way we solve the hamming distance is to validate the incoming strands are the same length.”</p><pre>raise ArgumentError.new unless strand1.same_length?(strand2)</pre><p>“Then we count the aggregate difference where there is a point mutation in the second strand when compared to the first.”</p><pre>self.zip(other).count{|(a,b)| a.point_mutation?(b) }</pre><h3>Limitations</h3><p>Type safety is an obvious concern when using delegation patterns that assume a specific inbound type. Whether or not this is acceptable is purely a mode of the total solution. For me, its often a great place to start, and we add guards later as we need them to reason about the remainder of the system.</p><h3>Complete Solution</h3><pre>class Nucleotide &lt; SimpleDelegator<br>  alias :point_mutation? :!=<br>end<br><br>class Strand &lt; SimpleDelegator<br>  def self.parse(str)<br>    arr = str.split(&quot;&quot;)<br>    new(arr.map {|x| Nucleotide.new(x)})<br>  end<br><br>  def same_length?(other)<br>    self.length == other.length<br>  end<br><br>  def -(other)<br>    self.zip(other).count{|(a,b)| a.point_mutation?(b) }<br>  end<br><br>  alias :hamming_distance :-<br>end<br><br><br>class Hamming<br><br>  def self.compute(str1, str2)<br>    strand1 = Strand.parse(str1)<br>    strand2 = Strand.parse(str2)<br>    raise ArgumentError.new unless strand1.same_length?(strand2)<br><br>    strand1.hamming_distance(strand2)<br>  end<br><br>end</pre><p>Thanks for reading. Sharing and applause appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7923c13c2328" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Borrowing From Math Class]]></title>
            <link>https://jedschneider.medium.com/borrowing-from-math-class-8afa6864151f?source=rss-5cbfadff4e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/8afa6864151f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Jed Schneider]]></dc:creator>
            <pubDate>Fri, 05 May 2017 22:04:37 GMT</pubDate>
            <atom:updated>2017-05-05T22:04:37.675Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3EWA7RsDIAiigK1vky0-A.jpeg" /><figcaption>special thanks to <a href="https://twitter.com/bencallahan">@bencallahan</a> for the shot!</figcaption></figure><p>A review of code samples and ideas from my talk ‘Borrowing from Math Class’ given at<a href="http://frontenddesignconference.com/"> Front End Design Conference, in St. Petersburg, FL, April 2017</a>.</p><p>The purpose of the code exercises below are to illustrate how we move from discrete solutions that rely on the combination of code and data, and move towards a more generic solution that relies on higher level functions to remove the code/data coupling.</p><p>In order to provide context, the code exercise I propose is to implement multiplication using only addition. That is to say that you have a calculator with only an add button and you want to implement a multiplication button.</p><h3>A discrete solution</h3><p>If we think about the operation of multiplication, it is simply the additive combination of groups of the same number. So for example `3 x 3 = 9` because we are adding three sets of three (represented here 3 sets of 3).</p><pre>||| + ||| + |||</pre><p>The first step is to see if we can write a function that can take a number and repeatedly add itself. We could define a triple function like so.</p><pre>triple = (x) =&gt; x + x + x;</pre><pre>triple(3) // 9</pre><h4>Parts of a function</h4><p>This is a side note to the content I provided in the talk but I realize in retrospect it might be nice to define the taxonomy of a function. For the function triple above we have several parts:</p><ul><li>The ‘variable’ <em>triple</em> that will for the life of the program be available to use. In some languages this would also be called a reference, or a symbol. It is a reference that is bound to the code on the right side of the equals sign.</li><li>The equals sign <em>=</em> is the assignment operation in JavaScript.</li><li>The argument signature (in this case <em>(x)</em>) describes the argument list that the function depends on to work. It is often described as the parameters of the function.</li><li>The function body <em>x + x + x</em> is the unit of work that will use the function parameters to return a new value from the result of the operations in the unit body.</li><li>The semicolon, in this case, represents the end of the statement.</li></ul><h4>Type signatures</h4><p>In many functional languages we would also include a type signature to describe the types of data that can be used by the function. In this case we intend to supply an integer x to the function, but it also can work for floats, and even strings, since the `+` function can be applied to string types in javascript.</p><pre>“e” + “d” + “f” // ‘edf’</pre><p>So while the use case we have for triple should be defined as</p><pre>triple :: Number -&gt; Number</pre><p>A function takes a number and returns a number, it should be more generically described like:</p><pre>// triple :: a -&gt; a<br> triple = (x)=&gt; x + x + x;</pre><p>Which can be thought of as a function that takes any generic type `a` and returns a new `a` of the same type.</p><p>We now have a solution. However, if we want to produce a function to quadruple a value then we must create a new ‘unique function’; but one that borrows most of its code from the triple function.</p><pre>// quadruple :: a -&gt; a<br>quadruple = (x) =&gt; x + x + x + x;</pre><p>extra credit, we could define the function like this as well:</p><pre>quadruple = (x) =&gt; x + triple(x);</pre><h3>Towards a more generic solution</h3><p>Going back to the first solution, what we realize, is that <em>the implementation of quadruple and triple are nearly identical</em>, it is only the number of `x`s in the function body that differ. <em>The applied function (addition) does not change</em>. When we see that pattern emerge, it should inform us that what we have is ‘data’ encoded in our program. So we can look at the above function and realize it contains three pieces of information, the input (`x`), the function (+), and the number of iterations we apply the function to `x`. So it would be nice if we could have an API for our new function that would allow us to abstract the process of the triple function to something like:</p><pre>// addMultiple : Number -&gt; Number -&gt; Number<br>/* addMultiple intentionally not defined here */</pre><pre>// triple :: Number -&gt; Number<br>triple = addMultiple(3)<br>// and the use it like<br>triple(3) // 9</pre><p>The type signature</p><pre>Number -&gt; Number -&gt; Number</pre><p>explains that we want to provide a Number (representing the number of times we are going to recursively add), and then another number to be recursively added, and finally return a number that is the result of the function execution. `triple` is the concrete solution of how we might use our abstract function to define a use case.</p><h3>More Math</h3><p>We can also leverage known theorems in mathematics to help in our quest. The Fundamental theorem of arithmetic explains that:</p><blockquote>every positive integer has a single unique prime factorization.</blockquote><p>In practice what this means is that we can take any positive divisible integer and describe it in terms of its set of unique non-divisible (prime) numbers. For example, if we want to describe the process of multiplying the number 3 by 40, eg `3 x 40`. We could define 40 in terms of its unique set of primes:</p><pre>40 = 20 * 2</pre><p>2 is a prime number, so we can add it to the list of primes, and then move to recursively identify the prime factors of 20.</p><pre>[2] // list of primes<br>20 = 10 * 2<br>[2,2] // add 2 to the list of primes<br>10 = 5 * 2<br>[2,2,2,5] // the complete list of primes that describes 40<br>2 * 2 * 2 * 5 // 40 (try it out if you don’t believe me)</pre><p>We can then apply the multiplicative factor of 3 to that number set to arrive at the product of `3 x 40` which is 120.</p><pre>3 * 5 * 2 * 2 * 2 = 120</pre><p>Another way to describe this is to say that we can take the input from one piece of the product and use it to feed into the next product, feeding the result of one evaluation to the next prime factor, for example:</p><pre>5 * 3 = 15<br>2 * 15 = 30<br>2 * 30 = 60<br>2 * 60 = 120</pre><p>Now we can see that if we had just two functions, a doubling function `d`, and a quintuple function `q`, we could solve the ‘times 40` problem.</p><pre>// d :: a -&gt; a<br>d = (a) =&gt; a + a ;</pre><pre>// q :: a -&gt; a<br>q = (x) =&gt; x + x + x + x + x;</pre><p>and then we can describe `times40` as:</p><pre>// times40 :: a -&gt; a<br>times40 = (x) =&gt; d(d(d(q(x))));</pre><p>Now we are relying on the composition of functions that are based on the prime factors of the desired number. We still have a code/data coupling problem. This function body `d(d(d(q(x))))` must exist. We have no way to ‘get rid’ of that code yet and so this function is only valid for the specific use case of multiplying by 40. But again we see there is a pattern of execution there that <em>seems like</em> we could have some abstraction for that would work for more than one specific solution.</p><h3>Function composition</h3><p>It turns out, that there is an abstraction that is readily available in functional programming to help us in this goal. You might recall from high school algebra the idea of function composition. you might have seen it in the style of:</p><pre>f(x) = 2 * x<br>g(x) = 5 * x</pre><pre>Question: <br> x’ = f(g(x))<br> What is the value of x’ when x is 3.</pre><pre>Solution:<br> g(3) = 15<br> f(15) = 30</pre><pre> x’ = 30</pre><p>In math we would describe this as functional composition and the shorthand notation for the above would be to say that</p><pre>x’ = f • g</pre><p>and would be read “x prime is equal to f of g”. Our function to multiply by 40 can be redefined in terms of composition of the ‘d’ and ‘q’ methods above</p><pre>d • d • d • q</pre><p>Read “d of d of d of q”.</p><p>In most functional languages, compose is a core concept, and most languages will have some notion of compose as a core function available. For the purposes of this article, I am relying on a <a href="http://ramdajs.com/">functional utility library</a> that provides some of these concepts directly for the JavaScript language. We could redefine our <em>times40</em> method in terms of <em>R.compose</em>.</p><pre>R = require(‘ramda’);</pre><pre>// times40 :: a -&gt; a<br>times40 = R.compose(d, d, d, q);</pre><p>It should be no surprise that compose in functional programming land ‘borrows’ directly from the mathematical definition. That is to say that the arguments to the compose function adhere to the same positional ordinance as the mathematical definition. The function `q` is the right most argument and is the first applied, rather than how we might anticipate based on other positional arrangements we are used to dealing with in other parts of computing. Eg, with arrays, the first position is the left most value. Operations like ‘pipe’, or ‘chain’ are usually applied left to right, and since many people are exposed first functional programming though data structure manipulation, the notion of chaining is also done left to right:</p><pre>[1,2,3].map(x =&gt; x + 1).reduce((acc, i) =&gt; acc + i, 0) // 9</pre><h3>Add Multiple</h3><p>Returning to our idea of <em>addMultiple</em>, we can use another type of functional composition. Let us review what we’d want our final API to look like:</p><pre>// triple :: Number -&gt; Number<br>triple = addMultiple(3);<br>// and the use it like<br>triple(3) // 9</pre><p>And to review the type signature.</p><pre>addMultiple :: Number -&gt; Number -&gt; Number</pre><p>Given our desired API, what returns from addMultiple is a function, so, lets start by doing that.</p><pre>addMultiple = (a)=&gt; (b)=&gt; 9;</pre><p>This would now work for `triple` because I’m hard coding 9 as a result, but the pattern now fits the use case. I am returning a function that will accept one more argument `b`, and then return the result. In order to make the internal method a little nicer I am going to write a method up front that I can use as a helper:</p><pre>add = (a,b)=&gt; a + b;</pre><p>The function composition I am going to use in this case builds on what we learned with composition above, but we will do it in a more subtle way using recursion. Recession relies on two or more primary cases. They are often referred to as boundary conditions. The boundary conditions typically determine when to recur, and when to stop and return a value. In the domain of <em>addMultiple</em> what might make sense is to ‘count down’ the number of times we’ve added multiple and end when we are at zero. For instance:</p><pre>addMultiple(3, 3)<br>addMultiple(2, 3)<br>addMultiple(1, 3)<br>addMultiple(0, 3) // return 9</pre><p>The other typical strategy in recursion is to pass the value you are building along with the signature. A possible function might look like this then:</p><pre>// _addMultiple (Number -&gt; Number -&gt; Number -&gt; Number<br>_addMultiple = (a,b,res=0)=&gt; 9</pre><p>By default the result value starts as 0, but we can supply that value in our recursive calls as necessary to a pass a value along. The next step is to define the edge conditions that will stop the recursive call, in this case, it is when `a` is 0.</p><pre>// _addMultiple (Number -&gt; Number -&gt; Number -&gt; Number<br>_addMultiple = (a,b,res=0)=&gt; if (a === 0) { return res } ; </pre><p>And then we can safely add the recursion.</p><pre>_addMultiple = (a,b,res=0)=&gt; {<br> if( a === 0 ) {<br>   return res;<br> } else {<br>   return _addMultiple( — a, b, b + res );<br> }<br>};<br></pre><p>We are sorta cheating here by using subtraction to decrement, so lets redefine the recursive call using our `add` helper function.</p><pre>_addMultiple = (a,b,res=0)=&gt; {<br> if(a === 0 ) {<br>   return res;<br> } else {<br>   return _addMultiple( add(-1, a), b, add(b, res) );<br> }<br>};</pre><p>finally we can wrap this up in another function such that the internals of our function are closed over:</p><pre>// addMultiple :: Number -&gt; Number -&gt; Number<br>addMultiple = function(a) {<br>  var _addMultiple = (a,b,res=0)=&gt; {<br>    if( a === 0 ) {<br>      return res;<br>    } else {<br>      return _addMultiple( add(-1, a), b, add(b , res) );<br>    }<br>  };</pre><pre>  // return a function waiting to apply b<br>  return (b)=&gt; _addMultiple( a, b );<br>};</pre><p>And now we have an implementation of our addMultiple function that could be used to implement triple. The astute reader will realize this is not a complete arithmetic solution. The astute comp. sci. major will also notify me that this could blow the stack since javascript does not support <a href="https://en.wikipedia.org/wiki/Tail_call">TCO</a> <em>yet</em>. You may also realize at this point that you could actually rename <em>addMultiple</em> to <em>multiply</em> and in fact, the <a href="http://ramdajs.com/">ramda</a> library I introduced earlier has an API compliant multiply function.</p><pre>R = require(ramda);<br>triple = R.multiply(3);<br>triple(3) // 9</pre><pre>R.multiply(3,3) // 9</pre><h3>Concluding remarks</h3><p>Given that Ramda provides us a multiply function with the desired API I describe is no coincidence. That library provides us the functions we want without the hard coded function bodies; and now we can define our time40 function like so.</p><pre>times40 = R.multiply(40);</pre><p>or to follow up on other ideas:</p><pre>d = R.multiply(2);<br>q = R.multiply(5);</pre><pre>times40 = R.compose(d, d, d, q);</pre><p>What I hope you walk away with is a deeper understanding of why we desire to remove the code/data coupling. This coupling binds our use case in the realm of discrete solutions. By understanding the underlying patterns in our code, and then abstracting these to data provided to the function, we start to move towards more unifying solutions. This is just one important idea exposed by ‘thinking functionally’ but I hope it has been useful.</p><p>I’d like to extend a special thanks to <a href="http://www.fuelixir.com/">Fuelixir</a> and <a href="http://www.accessmobileinc.com/">access.mobile</a>. Two organizations that make it possible to think about the things I like to think about. And also <a href="http://frontenddesignconference.com/">Front End Design Conference</a>, for the opportunity to speak!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8afa6864151f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mode Set Disbanded]]></title>
            <link>https://jedschneider.medium.com/mode-set-disbanded-cfd3abee8eb6?source=rss-5cbfadff4e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfd3abee8eb6</guid>
            <category><![CDATA[medium]]></category>
            <category><![CDATA[career-change]]></category>
            <category><![CDATA[love]]></category>
            <dc:creator><![CDATA[Jed Schneider]]></dc:creator>
            <pubDate>Fri, 19 Aug 2016 19:50:15 GMT</pubDate>
            <atom:updated>2016-08-19T19:50:15.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jihxrmRnOe6M_uOvS4Skrg.jpeg" /><figcaption>Go Fly A Kite</figcaption></figure><p>The band has dis-band-ed, never to be de-duped, or rebranded, and we’ve closed our doors. Mode Set does and will always continue to be close to my heart, but now only in the tshirts I won’t throw away, and the stickers, and wherever else I find that logo for many years to come.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BhtJHphyClXIplxf1YxpEQ.png" /></figure><p>It has been a great 4 years for me. Growth, failure, rising again from the ashes. I’ve had such a good time working with my fellow Mode Setters, it is kinda sur-real that I say good bye from a remote office, to friends I keep so close to my heart.</p><p>I’m bummed, of course. So is everyone else, my longtime friend and Mode Set founder said it best:</p><h3>Gabe Varela on Twitter</h3><p>The last 5 years have been the most challenging and fulfilling of my career. I&#39;m honored and proud to have worked with everyone at @modeset_</p><p>We worked really hard and built some incredible stuff. And always did our best.</p><p>Sometimes this is how it goes in business, and it sounds like everyone is going to land somewhere, doing more or less what they want.</p><p>As for myself, that is freelancing. At least for the short term. I’m going to give it a go and see what it shapes up like. There’s plenty of work already, and hopefully that remains the case.</p><p>Plus, I have some ideas of my own that I’m going to work at; see if I can find something interesting to build where hackable home economics, endurance sports training, and code intersect.</p><p>That’s it for now.</p><p>If you want to follow me on this journey, please follow, and you’ll be the first to know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfd3abee8eb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crushing Thoughts]]></title>
            <link>https://jedschneider.medium.com/crushing-thoughts-5c9f7050cfea?source=rss-5cbfadff4e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c9f7050cfea</guid>
            <category><![CDATA[cycling]]></category>
            <category><![CDATA[adventure]]></category>
            <dc:creator><![CDATA[Jed Schneider]]></dc:creator>
            <pubDate>Mon, 11 Jul 2016 03:52:04 GMT</pubDate>
            <atom:updated>2016-07-11T05:25:53.059Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IqjnJ3LJwSou9_a9BPK19A.jpeg" /><figcaption>Only 10 miles to go! Photo Credit: Katie Harlan</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*-HISwWCnnApqvd-pNT5Npw.jpeg" /><figcaption>The Col de Crush. photo credit: <a href="http://www.cottonsoxphotography.com/">http://www.cottonsoxphotography.com/</a></figcaption></figure><p>At mile 28, the road turns decidedly downward as racers plummet off the Col de Crush, descending 1,700 feet in a little less than 3.5 miles. As I picked up speed aboard my cross bike, and eyed down the hill towards the first turn, I grabbed a handful of smoothly actuated hydraulic powered disk brakes, and I smiled to myself. The road surface, the pitch, the exposure, it all reminded me of the <a href="https://www.youtube.com/watch?v=jU5BaZG6bTw">Kamikaze Downhill</a> of old. Reckoning back to pitching off the top of Mammoth Mountain at 50 mph on a steel hardtail with a first generation Rock Shox (RS1), poorly adjusted Onza cantilever brakes, and probably some early generation mountain bike tire with rubber durometer matching that of zip ties (and butyl tubes!!), I thought:</p><blockquote>I’ve done the Kamikaze on bikes less capable than this one.</blockquote><p>I laughed to myself, because I wasn’t sure anyone else here would even get that joke. This wasn’t, after all, a regrouping of 90’s era mountain bikers. This was the queen event of the now ever growing gravel racing scene in the United States. Many of the racers weren’t even alive when Jurgen Beneke set the speed record for the Mammoth course (I’m actually just speculating that’s true, based on recollection). Many racers know nothing different than carbon rims, and 10/11 speed, and brakes that work.</p><h4>Up is not Down</h4><p>I was decidedly less optimistic about my circumstances at mile 50, as we drug ourselves though a 4 mile sandy false flat (known as the Sarlacc Pit) back to the base of the Col de Crush, which we now had to ascend. Then I still had to climb another 7 or so miles to the 10,000 foot plateau where the air is quite thin and 4 hours in, the gas tank pretty empty. I thought mostly about what it must be like to be acclimated enough and good enough to actually look animated on this climb. Instead, I just trudged on, because any animation short of death was as good as it could get. Often when I’m in these situations, I admit to myself I’m not a climber. It doesn’t really prevent me from entering a race with a lot of climbing. It&#39;s like I forget I can’t do it. I don’t mind it. I like to train on climbs. I don’t even mind races with climbs I suck at. I just know I won’t be winning those races. I’m a sprinter climber. I need more brap, less blap.</p><p>There were people around me. I would occasionally pass someone, get passed by someone else. We all looked as shitty as we felt. The <a href="http://www.dnacycling.com/">DNA</a> feed zone is 1/2 way up the climb. You can look down from the feed zone and see people right below you, it seems like you can reach down and touch them almost, and it probably takes 15 minutes from there to actually reach the feed zone. It must be like watching a whole tour de france stage in slow motion. I kept pace with, mostly, the eventual second place finisher in my class. But the main group of age groupers, whom I had ridden through the flats of Circleville with, were now much too far to see on the climb. There were two women in that group that was now out of sight. I was most impressed by that. I thought to myself how awesome it is that endurance training has come so far as to elevate the the capacities of these women to be able to compete on this hard a course at this distance, head to head, with the men. There’s probably no greater indication of the depth and growth of our sport than the breakthrough results you witness in women’s cycling. I was also eventually passed by the wife of a longtime friend, who went on to finish third on the day. To each of those ladies, you had my respect before, but now you’ve punched my ticket, too. Great job!</p><h4>Your Race Ain’t Their Race</h4><p>My teammate Tyrel was foolish enough to enter the men’s open race. He toed up to the line with dudes like Robby Squire that will punch tickets at Tour of Utah later this year, and 3x olympian Todd Wells, and a host of other individuals that are highly qualified to ride way too fast at 9000 feet of elevation. I caught Tyrel on the flats after the Col, and it looked like the buzzards were after him. I told him to get on as I motored past, but I knew he had put in some major efforts, dug deep just to survive and stay in a group, and now was checked out. Props to him for finishing, knowing how bad it must have felt that last 13 miles. It was bad enough in my condition, and I had pretty much regulated every effort in my race.</p><p>It reminded me of two things. First, I belong in the age group classes. I have no interest or purpose racing the pros. Second, you can’t compare finish times. It’s easy to do. I did this morning. I looked and said <em>“oh, I woulda finished 23rd in the pros”</em>. Based on my finish time, that is true. But I don’t know that, because no one knows where they <em>“woulda finished”</em>, unless they toe into the race. Its an easy trap. One you should try to avoid. It creates a distorted version of your capacities. Yes, you can say you rode a higher average pace over the course of the course and finished faster than x dude in another class, but never make the mistake of assuming that being in his race, and being in yours, is the same thing.</p><h4>Finishing Thoughts</h4><p>I’ve pretty much committed this year to doing a handful of these mixed surface events to see which ones I can optimistically target for a result next year. I’m experienced enough to know good fitness takes 2 years or longer and I’m in no rush to get it back. I should qualify that I am rather pleased with 3rd yesterday, as I had assumed crossing the line I was so far down that I didn’t make the podium. I was pulling my bike off the rack in preparation to ride the 18 miles back to the car and drive home when I saw the podium for my age class and saw that 3rd wasn’t on the podium. I rushed to try to figure out where results were posted realized I was the missing dude, had a brief moment to savor that realization, and jumped up there in time for a quick photo. Whew. Thankfully, no one bothered bringing their bike up to to the podium. That’s such an awkward new phenomenon. Poor podium etiquette IMHO. If a sponsor is important enough to be in the podium shot, they should be on your jersey. But I digress into manners and tradition, which effectively makes me a curmudgeon, if my racing age didn’t tell you that already. So get off my lawn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*diCnHK9bJMdqj_47tEu8pg.jpeg" /><figcaption>See how nice the podium looks without a bike in the way. Photo Credit: Val Gibson (4th). He got 12 stitches and a pretty cool backpack.</figcaption></figure><p>There’s no optimism for an optimistic finish at Tushar next year. I need like 15 more miles of brap, and road conditions that make most people without years of riding marginally good bikes on bad terrain want to pull the brakes, and about 5 miles less climbing at hour 4. But I’ll be back because it’s awesome, and I’ve already forgotten I can’t climb.</p><h4>Thanks!</h4><p>Go ahead, and head on over to the <a href="http://tusharcrusher.com/">event site</a>, and give the analytics something to do. Follow the <a href="https://www.instagram.com/allegiantcycling/">Allegiant Cycling Team</a> on the instas, and go <a href="https://www.truedentistry.com/">visit Joe</a> next time you get your teeth kicked in. If you want to go real fast, the best option is to buy lots of bikes from <a href="http://www.bikeshop-lv.com/">The Bike Shop</a> (No kidding folks, isn’t that an awesome name for a bike shop?). If you can’t do that, at least go in and let your kids hang out on the sofa and watch TV while you explain to the guys there how that KOM was won. That’s what I do.</p><p>I also would like to send out a special thanks to Source Endurance. Both Trey Harrison and I were the only lowlanders on the podiums (that I saw) and we both rely on the folks over at SE to keep us on point. If you’re looking for a great coaching group,<a href="http://www.source-e.net/"> check ’em out.</a></p><p>Also, <a href="https://medium.com/@jedschneider">follow me</a>, especially if you like <a href="https://github.com/jedschneider">programming</a> AND <a href="https://www.strava.com/activities/635632851">cycling</a>, and recommend this by clicking the little heart, if it means something to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c9f7050cfea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Never use tabs — never, never, never.”]]></title>
            <link>https://jedschneider.medium.com/never-use-tabs-never-never-never-3281b9a03977?source=rss-5cbfadff4e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/3281b9a03977</guid>
            <category><![CDATA[coding-style]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bikeshedding]]></category>
            <dc:creator><![CDATA[Jed Schneider]]></dc:creator>
            <pubDate>Thu, 07 Jul 2016 05:32:15 GMT</pubDate>
            <atom:updated>2021-04-20T19:24:14.212Z</atom:updated>
            <content:encoded><![CDATA[<p>Edit: I no longer support this position. For an excellent reason to use tabs, please read this piece: <a href="https://www.reddit.com/r/javascript/comments/c8drjo/nobody_talks_about_the_real_reason_to_use_tabs/">https://www.reddit.com/r/javascript/comments/c8drjo/nobody_talks_about_the_real_reason_to_use_tabs/</a></p><p>This was a commit message I left a couple days ago in reaction to choosing `tabs` instead of spaces in a new project’s <a href="http://editorconfig.org/">editorconfig</a>. It seems like an extreme position. I’m not one for extreme positions, so of course there is some hyperbole in this statement. But really. Never use tabs. Here’s why.</p><h4>Whitespace is always significant</h4><p>There are a handful of languages (Python is the most notable example) where ‘whitespace is significant’. In other words, indentation is part of the structure of the code. So, whereas in Ruby where you might define a function (yes, yes, they are called methods in Ruby) like so:</p><pre>def hello_world<br>  puts “hello world”<br>end</pre><p>In Python you might write:</p><pre>def hello_world:<br>  print(&quot;hello world&quot;)</pre><p>In the Python example, no closing <em>end</em> tag is necessary. Rather the indentation indicates the function body; and the change in indentation ‘resets’ or closes the function body. Languages of this nature are referred to as having ‘significant whitespace’.</p><p>When the compiler (or interpreter) evaluates this function, it is counting whitespace characters to understand when the function ends, thus the mixture of tabs and spaces creates problems understanding how many characters indented the compiler is currently looking. Because while <em>tab-space-space</em> looks like the code is indented four columns in our editor, to the compiler, its only 3 whitespace characters.</p><p>But, here’s the rub,<strong> all languages have significant whitespace</strong>. If you don’t believe me, try opening up your javascript console and running:</p><pre>functionfoo(){console.log(‘foo’)}</pre><p>And then compare that to:</p><pre>function foo(){console.log(‘foo’)}</pre><p>Even in JavaScript, where you can go a long way with minimizing code, you can’t get rid of the space and evaluate the function as expected.</p><h4>One whitespace character is enough</h4><p>Whitespace is whitespace, unless you are a compiler, and then a tab and a space are two separate ASCII characters. In order to have a valid reason to choose to have two characters that <strong>mean the same thing</strong> but <strong>appear differently</strong> <strong>to the computer</strong> you’d have to prove, at least to me, that there is a difference in the semantics between a tab and a two spaces. It is equivalent to saying:</p><blockquote>“this color white is different than this other color white”</blockquote><p>Other languages like Clojure treat other symbols like commas as whitespace. Commas represent a separator, often in data, and can improve readability, but are not expressly necessary for the language’s compiler to worry about. Because commas and spaces are syntactically different, even if they evaluate to the same token type at compile time, there is a good use case for having two whitespace characters. Not so for characters that share the same syntax and semantics.</p><h4>Choose Spaces</h4><p>Until such time there is a language that uses tabs as all the whitespace in the program, there is no practical reason to choose tabs. It can only create problems in the case where tabs and spaces are actually different to the evaluation engine, and provides no semantic or syntactic clues to the readers or writers of the source code. There’s no upside. And while you’re at it, get rid of all those <a href="http://programmers.stackexchange.com/questions/29075/difference-between-n-and-r-n">windows carriage returns</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3281b9a03977" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The secret life of [context] in underscore and lodash]]></title>
            <link>https://jedschneider.medium.com/the-secret-life-of-context-in-underscore-and-lodash-722ce3e24608?source=rss-5cbfadff4e79------2</link>
            <guid isPermaLink="false">https://medium.com/p/722ce3e24608</guid>
            <dc:creator><![CDATA[Jed Schneider]]></dc:creator>
            <pubDate>Tue, 10 Mar 2015 15:58:43 GMT</pubDate>
            <atom:updated>2015-03-13T16:51:01.112Z</atom:updated>
            <content:encoded><![CDATA[<p>If you spend any time using either <a href="https://lodash.com/">lodash</a> or <a href="http://underscorejs.org/">underscore</a> as a utility library, you probably use a few functions that have a mysterious optional final parameter in the documentation. In underscore it is defined as <em>[context] </em>and in lodash <em>[thisarg]</em> (I will be illustrating the concepts with underscore from here on, but everything mentioned also applies in lodash). You may see certain references to what this context parameter does, and some simple examples on <a href="http://stackoverflow.com/questions/4946456/underscore-js-eachlist-iterator-context-what-is-context">StackOverflow</a> on how it could be used, but for me, what I saw never really helped much. I hope this will help you understand where it can be used and why it’s super useful.</p><p>As an example, we could look at the documentation for <a href="http://underscorejs.org/#every">_.every</a>. You could write a function to determine if all elements are equal to 1.</p><pre>_.every( [1,1,1,2], function(i){<br>  return _.isEqual(1,i)<br>}) // false</pre><p>And we could clean that up a bit with<a href="http://underscorejs.org/#partial"> _.partial</a></p><pre>_.every([1,1,1,2], _.partial(_.isEqual, 1)) // false</pre><blockquote>Side Note: Any time we see that pattern where we are taking an argument into a function and there is a simple evaluation of another function inside (like _.isEqual) this is a great spot to use _.partial to construct the intended function without another anonymous function declaration; and you get rid of having to having to specify the return.</blockquote><p>The previous example’s use of <em>_.every</em> is the basic case. Optionally, it takes a third parameter of <em>[context]</em>. To get a deeper understand, we need a better example.</p><h4>Comparison of JavaScript Objects</h4><p>So let’s say we have two array of objects that we want to compare.</p><pre>var array1 = [<br> { name: ‘Jane’, age: 58},<br> { name: ‘John’, age: 25}<br>]</pre><pre>var array2 = [<br> { name: ‘John’, age: 25},<br> { name: ‘Jane’, age: 58} <br>]</pre><p>We can see that they are the same, but in a different order. It seems like we should easily be able to use underscore to give us equality. Let’s try it out.</p><pre>(_.isEqual(array1, array2)) // false</pre><p>Darn. Not what we expect. It seems like underscore isn’t going to do a deep compare, and Array equality is not as robust as we’d like in JavaScript. This means we have to be a bit more creative.</p><p>We could do something like sort by a specific key, but this may fall down if our data objects get more keys.</p><pre>_.isEqual(<br>  _.sortBy(array1, ‘name’), <br>  _.sortBy(array2, ‘name’)<br>) //true</pre><p>For this example assume this won’t work because (of some crazy business requirements) what we really want is to determine if the list in question is a <a href="http://en.wikipedia.org/wiki/Subset">subset</a> of the other list.</p><p>Let’s see if we can use <a href="http://underscorejs.org/#some">_.some</a> to check if one object is included in another collection.</p><pre>obj = { name: ‘John’, age: 25 }</pre><pre>_.some(array1, _.partial(_.isEqual, obj)) // true</pre><p>Can you think of a way to do this against two separate lists? There are a couple options that might come to mind.</p><pre>_.every([array1, array2], function(x){/* split and compare here */}</pre><p>That seems a bit contrived, and we can still only iterate over values in a single list. How about this?</p><pre>_.every( [array1], function(x){<br>  return _.some(array2, function(x){/* logic here */})<br>}</pre><p>But if we do something like that we are no longer <a href="http://en.wikipedia.org/wiki/Referential_transparency_(computer_science)">referentially transparent</a>, because we refer to an outside (<em>array2</em>) variable from within our closure.</p><p>Also, by referencing <em>array2</em>, we bind any use of this function to that specific comparator array in the future. so if we want a comparator for another array, we need to expressly construct a new function that is identical to the above, with a different array reference. What we really want is a nice way to pass in the other array, and to be able to configure a function via composition for specific use cases.</p><h4>The magic of [context]</h4><p>The simple definition of context is the binding of <em>this</em> that will be used by the iterator. That seems super abstract so lets explore what that means in practice. In our last attempt we thought we might try something like:</p><pre>return _.some(array2,...)</pre><p>Well, if array2 was the context, then we’d be set because we could say:</p><pre>return _.some(this,...)</pre><p>So, lets see how that unfolds.</p><pre>function iterator(item){<br> return _.some(this, function(x){<br>   return _.isEqual(item, x)<br>  })<br>}</pre><p>We can, again, clean that up with <em>_.partial</em></p><pre>function iterator(item){<br>  return _.some(this, _.partial(_.isEqual, item))<br>}</pre><blockquote><em>YMMV: I’m not going to claim this iterator function fits every edge case (use set operations in real life). We just need something simple enough to work through.</em></blockquote><p>And then the application of that with <em>_.every.</em></p><pre>_.every(array1, iterator, array2) // true</pre><h4>Next Steps</h4><p>At this point we have a pretty awesome comparator, but we might be able to take it a little further with our function composition. We could create custom functions, configured for a specific array case.</p><pre>array1IsASubsetOf = _.partial(_.every, array1, iterator)</pre><p>And then we can use it like so.</p><pre>array1IsASubsetOf(array2) // true</pre><p>And this is great, because now we can use that function as an argument to other underscore methods to, for example, filter a whole list of lists for arrays that are subsets of our <em>array1</em>.</p><pre>_.filter(arrayList, array1IsASubsetOf)</pre><h4>No Loops (kinda)</h4><p>When you take a look at the final code, I hope you find it devoid of most of the things we normally expect to see when comparing two lists of data. For one, there’s no loops (at least ones that we define), for another, there is no global pollution of intermediate values. Programming with functions, and dynamic scoping can be challenging, but really fun once you start to crack the surface.</p><p>Here is the entirety of the code for completeness. And a <a href="http://jsfiddle.net/y4h5rkpo/">jsfiddle</a> to play with.</p><pre>var array1 = [<br> { name: ‘Jane’, age: 58},<br> { name: ‘John’, age: 25}<br>]</pre><pre>var array2 = [<br> { name: ‘John’, age: 25},<br> { name: ‘Jane’, age: 58} <br>]</pre><pre>var array3 = [<br>    { name: &#39;John&#39;, age: 25},<br>    { name: &#39;Jane&#39;, age: 58},<br>    { name: &#39;Josh&#39;, age: 12}<br>]</pre><pre>var array4 = [<br>    { name: &#39;Philip&#39;, age: 25},<br>    { name: &#39;Jane&#39;, age: 58}           <br>]</pre><pre>function iterator(item){<br>  return _.some(this, _.partial(_.isEqual, item))<br>}</pre><pre>subsetsOfArray1 = _.partial(_.every, array1, iterator)</pre><pre>_.filter([array1, array2, array3, array4], subsetsOfArray1)</pre><p>Thanks for reading!</p><p>Special Thanks to <a href="https://twitter.com/sgrif">Sean Griffin</a>, <a href="https://twitter.com/billygriffin22">Billy Griffin</a>, and <a href="https://twitter.com/BreeThomas33">Bree Thomas</a> for technical review.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=722ce3e24608" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>