<?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 Gustaf Holm on Medium]]></title>
        <description><![CDATA[Stories by Gustaf Holm on Medium]]></description>
        <link>https://medium.com/@primalivet?source=rss-3e4d1abc12b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VY7aq-yF7kwF4kTL7mtKzA.jpeg</url>
            <title>Stories by Gustaf Holm on Medium</title>
            <link>https://medium.com/@primalivet?source=rss-3e4d1abc12b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 18 May 2026 09:20:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@primalivet/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[Currying and Composing your own versions of Reduce, Filter and Map]]></title>
            <link>https://codeburst.io/currying-and-composing-your-own-versions-of-reduce-filter-and-map-487ab786c643?source=rss-3e4d1abc12b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/487ab786c643</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gustaf Holm]]></dc:creator>
            <pubDate>Wed, 07 Aug 2019 14:08:50 GMT</pubDate>
            <atom:updated>2019-08-08T06:50:35.377Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is a follow up on my previous post, <a href="https://codeburst.io/reduce-filter-and-map-without-reduce-filter-and-map-787c21671c95">Reduce, Filter and Map without Reduce, Filter and Map</a> in which I showed how to implement your own versions of the array functions. Here we’ll alter those functions a bit so that we can make curried versions of them and later on compose them.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svEiTlSzYQDXjsGgqquVnw.png" /></figure><p>So if you don’t know how to implement reduce, map and filter or if you just wan’t to take a look at how I did it. Head over to <a href="https://codeburst.io/reduce-filter-and-map-without-reduce-filter-and-map-787c21671c95">Filter and Map without Reduce, Filter and Map</a>, read it, understand it, come back here 😊.</p><p><a href="https://codeburst.io/reduce-filter-and-map-without-reduce-filter-and-map-787c21671c95">Reduce, Filter and Map without Reduce Filter and Map</a></p><p>So in the <a href="https://codeburst.io/reduce-filter-and-map-without-reduce-filter-and-map-787c21671c95">previous post</a> I got a question on how to chain the self implemented versions of reduce, filter and map 🤔. I thought it was a good question and my way of combining the functions would be to compose them instead of chaining them.</p><p><em>☝ Also the way I’ve implemented them, as basic functions, there’s no </em><em>this keyword so chaining as the JavaScript built in versions wouldn’t really be an option. I could rewrite all of it as a module pattern but prefer the basic functions. Another way is to override the built in Array methods but that’s a BIG no no!</em></p><p>So to compose these functions we need to make sure they all accept arrays as arguments and also returns arrays, so that the result from on function can be the input to the next one.</p><p>We also want to be able to “prep” our composable functions. For example if I want to filter out odd number from an array and then double the remaining numbers I would like it to look something like this when calling.</p><pre>const double = x =&gt; x * 2<br>const even = x =&gt; x % 2 === 0;</pre><pre>const removeEvenAndDouble = compose(map(double), filter(even))<br>removeEvenAndDouble([1,2,3,4,5])</pre><p>These composed functions create a flow where I would expect the returned value to be an array of [4,8]. So when I say “prep” functions I mean that I’ve already told map to use the double callback and filter to use the even callback. So when I call removeEvenAndDouble with the [1,2,3,4,5] array the array should be passed to the filter function, which runs the even function on each item, then returns the filtered array to the map function which runs the double function on each item.</p><p>So the array needs to be passed as the last argument to map and filter (the same goes for reduce). The arguments must also be passed one by one, so as long as the function doesn’t have all the arguments it need it will just sit there and relax. In other words we need curried functions.</p><p>I was also asked how to debug when combining / chaining / composing the self implemented functions. You could just use the browser dev tools and set breakpoints like any other program. But if you want a more “console.log fashion” we can use a “trace” function, it takes a label, returns a function that takes a value (it’s curried 😉), it prints the label and the value and returns the value. It looks like this.</p><pre>const trace = label =&gt; value =&gt; {<br>  console.log(label, value)<br>  return value<br>}</pre><p>Really simple! The trace function above is already a curried function as it takes one argument at the time and the “data” as it’s last argument. We could take all arguments at once and then write another function to curry the trace function. That way we have both a regular and a curried version of the trace.</p><h3>A Function to Curry Functions</h3><p>This function might give you a headache 🤯, it’s very compressed. Read it twice.</p><pre>const curry = func =&gt; <br>  (...args) =&gt; <br>    (args.length &lt; func.length) <br>    ? (...moreArgs) =&gt; curry(func)(...args, ...moreArgs) <br>    : func(...args);</pre><p>Basically it takes a function, checks how many arguments that function needs to run. Compare the needed number of arguments to the arguments given. If it’s enough it runs the function with the given arguments. If it’s not enough arguments it returns a anonymous function that takes more arguments and then recalls the curry function with the old arguments plus the new ones and keeps doing that until it has all the arguments.</p><p>Here’s an example with the trace function.</p><pre>const trace = (label, value =&gt; {<br>  console.log(label, value)<br>  return value<br>}</pre><pre>const curriedTrace = curry(trace)</pre><pre>trace(&quot;hello&quot;, &quot;world&quot;) // logs &quot;hello world&quot;<br>curriedTrace(&quot;hello&quot;)(&quot;world&quot;) // logs &quot;hello world&quot;</pre><p>As you’ve already figured out we’ll use this function to make curried versions of our reduce, filter and map from <a href="https://codeburst.io/reduce-filter-and-map-without-reduce-filter-and-map-787c21671c95">the previous post</a>. But first we need to switch the arguments order.</p><h3>New versions of Reduce, Map and Filter with switched arguments</h3><h4>Reduce</h4><p>This is the same reduce as in <a href="https://codeburst.io/reduce-filter-and-map-without-reduce-filter-and-map-787c21671c95">the previous post</a>, but with the array argument last. This also affects the internal argument order in map and filter (as we call reduce inside those functions) which we’ll handle below.</p><pre>const reduce = (cb, initialValue, array) =&gt; {<br>  let result = initialValue;<br>  array.forEach(item =&gt;<br>    result = cb.call(undefined, result, item, array));<br>  return result;<br>};</pre><h4>Map and Filter</h4><p>Same goes here, array is the last argument. We’re also calling our reduce function with the array argument last.</p><pre>const map = (func, array) =&gt;<br>  reduce((result, item) =&gt;<br>    result.concat(func(item)), [], array);</pre><pre>const filter = (func, array) =&gt;<br>  reduce((result, item) =&gt;<br>    func(item) ? result.concat(item) : result, [], array);</pre><h4>Make the curry</h4><p>Now it’s dead simple to create curried versions of Reduce, Map and Filter, or any other function for that matter.</p><pre>const curriedMap = curry(map);<br>const curriedFilter = curry(filter);<br>const curriedReduce = curry(reduce);</pre><h3>Composing</h3><p>So now we got tracing to log the value with a label. We got the new versions of our functions with the array argument last and a function to curry it all! But we still need a function to compose our curried functions with. And as we saw in the beginning of this little text it should take some functions as argument, return another function which takes the initial value as it’s argument, which is passed to the first (actually the last, it runs from the bottom up) function and the result from the first function should be the input to the next and so on until we reach out last (first 😉) function. Then we get the result of the chain/compose flow. So here’s a implementation of the compose function.</p><pre>const compose = (...funcs) =&gt; <br>  initValue =&gt; <br>    reduce(<br>     (funcResult, func) =&gt; func(funcResult), <br>     initValue, <br>     funcs.reverse()<br>   );</pre><p>It takes functions as it’s argument and turns it into a array of function with the rest “…” operator. This returns a function which takes a initial value. Then it calls our implementation of reduce with a callback function, the initial value and the functions array, reversed as it’s how compose should work, bottom up, right to left, backwards.</p><h3>Dummy Functions</h3><p>We need some dummy functions to create a working example of composing our curried functions. Here they are.</p><pre>const double = x =&gt; x * 2;<br>const even = x =&gt; x % 2 === 0;<br>const sum = (sum, x) =&gt; sum + x;</pre><h3>Put it together</h3><p>Only thing left now is to Create the chain of functions, it runs from the bottom up, as “compose” functions should. Call the chain of function with a initial array.</p><pre>const chain = compose(<br> trace(&#39;after curried reduce&#39;), // logs 12<br>  curriedReduce(sum, 0),        // array gets summed<br>  trace(&#39;after curried map&#39;),   // logs [4,8]<br>  curriedMap(double),           // array gets doubled<br>  trace(&#39;after curried filter&#39;),// logs [2,4]<br>  curriedFilter(even)           // array gets filtered<br> );</pre><pre>chain([1,2,3,4,5]);</pre><p>That’s it. Thanks for reading. Hope you learned something. Bye! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=487ab786c643" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/currying-and-composing-your-own-versions-of-reduce-filter-and-map-487ab786c643">Currying and Composing your own versions of Reduce, Filter and Map</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage your dotfiles with ease]]></title>
            <link>https://medium.com/@primalivet/manage-your-dotfiles-with-ease-fca54f16c6c6?source=rss-3e4d1abc12b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fca54f16c6c6</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[dotfiles]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gustaf Holm]]></dc:creator>
            <pubDate>Thu, 13 Jun 2019 15:01:00 GMT</pubDate>
            <atom:updated>2019-06-13T15:01:00.964Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let a little <a href="https://www.gnu.org/software/stow/">GNU program called Stow</a> do the job.</h4><p>A lot of people, including me, version control their dotfiles.</p><p>Most configs and settings for editors, terminals and alike live in your home folder “~”. But you don’t want to version control your whole home dorectory. So it’s necessary to keep all the configs and setting in a separate directory and move or link the config files to your home directory programmatically.</p><p>How do people do that? Usually with some complicated shell scripts that they write themselves. There’s nothing wrong in that, BUT I “found” this little GNU command line program called Stow. It’s brilliant for managing your dotfiles even though that’s not its intended use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhxuecWv8a6HOVLzwJrTYA.png" /></figure><p>Lets take an example from the text editor Vim. It uses a .vimrc file and a .vim directory which both live inside the home directory. My .vimrc file and .vim directory are version controlled in my dotfiles git repository. It can obviously be cloned to any place in the file system. For example, lets say I’ve cloned my dotfiles repository to my home directory. My dotfiles directory looks like this.</p><pre>/<br>/vim<br>/vim/.vimrc<br>/vim/.vim</pre><p>Using Stow, all I’ve to do is to cd into my dotfiles directory and “Stow” the dotfiles subdirectory for the program I want to link up in my home directory.</p><pre>$ cd ~/dotfiles<br>$ stow vim</pre><p>This creates a symbolic link in my home directory for each file and directory inside my dotfiles/vim directory. As we can see Stow’s default behavior is to create symbolic links one level up the directory tree from where the command was ran.</p><p>If I want to clone my dotfiles repository to another place on the file system I start off the same by cd path/to/dotfiles. Then I just pass in my home directory as the target -t argument like stow vim -t ~. Now Stow will create symbolic links inside my home directory to my dotfiles/vim/.vimrc and dotfiles/vim/.vim wherever the dotfiles directory is located.</p><p>Smooth! 😎</p><h4>Directories inside directories</h4><p>In the case of Vim it uses the .vim folder for lots of stuff. I have specific settings for each filetype in my .vim directory. So settings for Python files live inside dotfiles/vim/.vim/after/ftplugin/python.vim. When I “Stow” the dotfiles/vim directory with stow vim -t ~ it creates a symbolic link at ~/.vim to dotfiles/vim/.vim. But Vim also uses ~/.vim for other stuff, like the file explorer history and it’s a suitable place to keep plugins for example.</p><p>But I don’t want to Vim’s file explorer history or pluggins in my dotfiles to be placed inside my dotfiles/vim/.vim directory. So I need a way to create a new directory for the dotfiles/vim/.vim/after directory at the target (my home folder). Stow comes with a handy argument for this, --no-folding . So by typing stow --no-folding vim -t ~ Stow creates the .vim folder in my home directory and symlinks the .vim/after to dotfiles/vim/.vim/after . So now the Vim file explorer can do it’s thing inside ~/.vim and the fantastic Vim plugin manager <a href="https://github.com/junegunn/vim-plug">vim-plug</a> can place pluggins inside ~/.vim/plugged while still keeping those files outside of my dotfiles repository.</p><p>🤯 This last bit with subdirectories might come across as a bit complicated, see the <a href="https://www.gnu.org/software/stow/manual/stow.html#tree-folding">Stow manual on tree-folding</a> for more infoillurmation and be sure to just try it out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fca54f16c6c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Usefull GNU Readline settings]]></title>
            <link>https://medium.com/@primalivet/usefull-gnu-readline-settings-5ee8c42ab409?source=rss-3e4d1abc12b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ee8c42ab409</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[command-line]]></category>
            <dc:creator><![CDATA[Gustaf Holm]]></dc:creator>
            <pubDate>Tue, 25 Dec 2018 10:21:00 GMT</pubDate>
            <atom:updated>2018-12-25T22:06:41.661Z</atom:updated>
            <content:encoded><![CDATA[<h4>I thought I would share some of the settings found in my .inputrc GNU<a href="https://www.gnu.org/software/readline/"> Readline </a>configuration file.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FHc6lmpy0xJbjAIjdy_9KA.png" /></figure><p>As you’ve already ended up on this page you probably already know what GNU Readline is, but for those who don’t, here’s the one-sentence explanation:</p><blockquote>GNU Readline is a software library that provides line-editing and history capabilities for interactive programs with a command-line interface, such as Bash.</blockquote><p>Most users come in contact with GNU Readline through the “Bash prompt” or<br>programs like the MySQL shell. Most of the GNU Readline settings can be set in each programs respective configuration file. Like .bashrc. But the .inputrc is specifically for GNU Readline. So the settings there will be inherited by any program that implements GNU Readline. In other words, same settings almost everywhere 🤓.</p><h3>Settings</h3><pre>set bell-style none</pre><p>Turns off any annoying beeps bash makes, like the one when you hammer the<br>backspace while you’re at the start of the prompt.</p><p>No more “ding ding ding” 🙌!</p><pre>set colored-stats on<br>set colored-completion-prefix on</pre><p>The first option, colored-stats, makes your completions colored just like when you ls --color=auto. The second line puts some color on the current prefix used to search possible completions. For example if you type apt- and then hit tab, the apt--part will be highlighted when GNU Readline gives you completion suggestions like apt-get and apt-cache.</p><pre>set completion-ignore-case on<br>set completion-map-case on</pre><p>The first line is self explanatory, it turns off case sensitivity. The second<br>option, completion-map-case isn’t a great label. What it does is to treat<br>hyphens - like underscores _ and vice versa. This option only works when completion-ignore-case is turned on, like above.</p><pre>set echo-control-characters off</pre><p>When your timing is off or your brain stops working when jumping around the<br>command line you just throw combinations like Ctrl+C for no reason. And<br>GNU Readline is polite, so it just thinks “what the hell” and echo out your<br>combo 🤜🤜🤛👊🤛🤜. This settings tells GNU Readline that it doesn’t have to bother.</p><pre>set menu-complete-display-prefix on</pre><p>When hitting Tab to search possible completions, GNU Readline will show you the common prefix for the possible completions and present them in a list. For example, if I have a package.json file and a package-lock.json file running vi p + Tab will make GNU Readline list the two files and append<br>to your prompt up to vi package. This is because all (both) possible<br>completions share the prefix `package`.</p><pre>$if Bash<br> Tab: menu-complete<br>$endif</pre><p>By default, Bash binds a function called complete to the Tab key. That<br>function show a list of possible completions and completes up to the lowest<br>common prefix. If you keep hammering on the Tab key, just repeats this action. With Tab bound to menu-complete. Bash will cycle through the options as you keep hammering the Tab key, much better! There’s also menu-complete-backwards, hmm?? 🤔😉</p><h3>There’s more</h3><p>If you’re using the GNU Readline (command line) a lot and want to tweak and bend it. Fire up a terminal emulator and man readline.</p><p>Hope you had a nice read and you learned something. Bye. 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ee8c42ab409" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common Way of Resizing Windows/Panes in Vim and Tmux]]></title>
            <link>https://codeburst.io/common-way-of-resizing-windows-panes-in-vim-and-tmux-9b88def886c6?source=rss-3e4d1abc12b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b88def886c6</guid>
            <category><![CDATA[code-editor]]></category>
            <category><![CDATA[vim]]></category>
            <category><![CDATA[tmux]]></category>
            <dc:creator><![CDATA[Gustaf Holm]]></dc:creator>
            <pubDate>Tue, 18 Dec 2018 08:34:57 GMT</pubDate>
            <atom:updated>2018-12-21T18:58:13.808Z</atom:updated>
            <content:encoded><![CDATA[<h4>It’s not often, but once in a while I want to resize a window in Vim or a pane in Tmux. And every time 😒, I’m thinking that I should rebind some keys to make the two programs more similar.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6UL41bVLOUS9rhP2eFD-g.png" /></figure><h3>Vim</h3><p>So in Vim I use the default bindings for resizing buffers. But I’ve tweaked them a bit 😏. The only thing I’ve done is to rebind the keys in whatever mode, so just noremap, to increase and decrease by 5 instead of the default 1.</p><pre>noremap &lt;C-w&gt;+ :resize +5&lt;CR&gt;<br>noremap &lt;C-w&gt;- :resize -5&lt;CR&gt;<br>noremap &lt;C-w&gt;&lt; :vertical:resize -5&lt;CR&gt;<br>noremap &lt;C-w&gt;&gt; :vertical:resize +5&lt;CR&gt;</pre><p>More info in Vim help system at :h window-resize.</p><h3>Tmux</h3><p>In Tmux I bind the same keys used in Vim (now with Tmux prefix obviously, I use Ctrl+A like most others). Here I change the value by 10 instead of 5. Only reason for this is that it feels right. I think the system are in columns and rows or something, but that doesn’t really matter.</p><pre>bind-key -r ‘+’ resize-pane -U 10<br>bind-key -r ‘-’ resize-pane -D 10<br>bind-key -r ‘&lt;’ resize-pane -L 10<br>bind-key -r ‘&gt;’ resize-pane -R 10</pre><p>The -r flag passed into the binding makes it repeatable. So when you press your prefix, you have a certain time to hammer &gt; for example to make the pane increase to the right. The time you got depends on your repeat-time option which defaults to 500 milliseconds.</p><p>Thanks for reading 🙌👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b88def886c6" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/common-way-of-resizing-windows-panes-in-vim-and-tmux-9b88def886c6">Common Way of Resizing Windows/Panes in Vim and Tmux</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing in Express with Promise-based Middleware and Controllers]]></title>
            <link>https://codeburst.io/unit-testing-in-express-with-promise-based-middleware-and-controllers-7d3d59ae61f8?source=rss-3e4d1abc12b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d3d59ae61f8</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Gustaf Holm]]></dc:creator>
            <pubDate>Fri, 25 Aug 2017 14:26:18 GMT</pubDate>
            <atom:updated>2017-08-26T10:51:28.131Z</atom:updated>
            <content:encoded><![CDATA[<h4>Easier unit tests in ExpressJS by returning Promises from middleware.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvUF27bVr-GVjWE5FidzEg.gif" /></figure><p>A fat stack of callbacks are usually the way to use route middleware/controllers in good old Express tutorials around the web. It works fine but is usually a mess to unit test in my opinion 🙄. Especially when the middleware/controllers stack grows to include authentication, validation etc.</p><h4>A note on Middleware, Controllers, Route handlers in Express</h4><p>Express is unopinionated on how you structure flow control in routes. So words like controllers, middleware and route handlers might mean different things or for the most part kind of the same thing 😕, confusing I know. However, there are some great <a href="https://github.com/expressjs/express/tree/master/examples">examples on how to setup your routes at Express GitHub repository</a>.</p><p><em>☝️ The structure I use for unit testing in this tutorial can be applied to any middleware/controller/route handler in express. So don’t worry about that.</em></p><h3>How routes usually are structured</h3><p>The very very simple example show the “classic” way of setting up a route.</p><pre>app.get(&#39;/endpoint&#39;, verifyToken, validateRequest, getThings);</pre><p>In this structure verifyToken and validateRequest has to call next() at some point so that the request can move along the stack. This makes unit test on a specific middleware harder than it needs to be. So, many tutorials end up writing something more like a integration test for the whole route. With that kind of test you don’t have to figure out if a middleware calls next(). Of course it can be done with stuff like <a href="http://sinonjs.org/">SinonJS</a> but I think it makes things more complicated then they need to be. Especially when you add more routes and use the same middleware in multiple routes.</p><h3>Middleware as Promises</h3><p>A first step to get around this issue is to structuring my middleware/controllers around Promises. That way I can use async/await or .then().catch() on my controllers inside each route. In other words I control the calling of next() inside the route and not the controller.</p><p>Let’s look at an example. Here’s a over simplified example of the verifyToken controller.</p><pre>exports.verifyToken = (req, res) =&gt; <br>  new Promise(async (resolve, reject) =&gt; {<br>    const token = req.cookies.token;<br>    if (token) {<br>     try {<br>       const user = await tokenFramework.verify(token, secret);<br>       req.user = user;<br>       resolve({ message: &#39;You have a valid token&#39; });<br>     } catch (error) {<br>       reject({ message: &#39;Not a valid token&#39;, error });<br>     }<br>  };</pre><p>And another example of the getThings controller.</p><pre>exports.getThings = (req, res) =&gt; <br>  new Promise(async (resolve, reject) =&gt; {<br>    try {<br>      const things = await Thing.find({req.params.id});<br>      resolve({ things });<br>    } catch (error) {<br>      reject({ message: &#39;Could not retrive things&#39;, error })<br>    }<br>  };</pre><p>As you might figure out the main thing here is to return a Promise which will resolve() or reject() based on some logic inside the middleware/controller.</p><h4>Handle Promises in the Route</h4><p>As each middleware returns a promise I can just call then() on it and really do whatever I want. This is especially useful as it’s much clearer when next() is called and what happens throughout the middleware stack.</p><p>And of course, it makes unit testing specific middleware a breeze! ✌️</p><pre>app.get(&#39;/endpoint&#39;,<br>  (req, res, next){<br>    verifyToken(req, res)<br>      .then(() =&gt; next())<br>      .catch(err =&gt; res.json(err))<br>  },<br>  (req, res, next){<br>    validateRequest(req, res)<br>      .then(() =&gt; next())<br>      .catch(err =&gt; res.json(err))<br>  },<br>  (req, res, next){<br>    getThings(req, res)<br>      .then(response =&gt; res.json(response))<br>      .catch(err =&gt; res.json(err))<br>  };</pre><p>If you don’t play nice with .then() you can use async/await together with try/catch like that 👇.</p><pre>...<br>async (req, res, next) {<br>  try {<br>    const response = await validateRequest(req, res);<br>    next();<br>  } catch (error) {<br>    res.json(error)};<br>},<br>...</pre><p><strong>Quick summery</strong>: Since I return a Promise from every controller middleware I moved the logic of calling next() to the route, very simple. If the promise resolves, call next() and proceed to the next middleware/controller or send the response to the client.</p><h3>Run your tests</h3><p>Now you just import the middleware in your test and the only thing you have to fake is the req and res . Use something like <a href="https://www.npmjs.com/package/node-mocks-http">node-mocks-http</a> for that.</p><p>Below I use tape for testing. I really like tape for it’s simplicity and it supports asynchronous testing in a clear simple way.</p><pre>const test = require(&#39;tape&#39;);<br>const httpMocks = require(&#39;node-mocks-http&#39;);<br>const verifyToken = require(&#39;path/to/verifyToken&#39;);</pre><pre>test(&#39;verifyToken resolves with a success message&#39;, (assert) =&gt; {<br>  const req = httpMocks.createRequest({ <br>    cookies: { token: &#39;blablabla&#39; }<br>  });<br>  const res = httpMocks.createResponse();</pre><pre>  return verifyToken(req, res).then((response) =&gt; {<br>    ...<br>    assert.equal(typeof response.message, &#39;string&#39;);<br>    ...<br>  });<br>});</pre><pre>test(&#39;getThings resolves to an array of objects&#39;, (assert) =&gt; {<br>  const req = httpMocks.createRequest({ <br>    params: { id: &#39;12345&#39; }<br>  });<br>  const res = httpMocks.createResponse();</pre><pre>  return getThings(req, res).then((response) =&gt; {<br>    ...<br>    assert.equal(Array.isArray(response.things), &#39;true&#39;);<br>    ...<br>  });<br>});</pre><p>Since each controller now is self contained and only require a request and response as their arguments I can mock those and just call the function. No need to import your whole Express app or anything like that. Though if your working against a database, you have to connect to it in some way.</p><p>I’ve put together an <a href="https://github.com/primalivet/events-thing-server">app on GitHub that use Express, MongoDB and JSON Web tokens</a> and has controllers/middleware to handle users, things (events in this case) and tokens. I hope you find it useful.</p><p>That’s it. Thanks for reading! 👋😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d3d59ae61f8" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/unit-testing-in-express-with-promise-based-middleware-and-controllers-7d3d59ae61f8">Unit testing in Express with Promise-based Middleware and Controllers</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce, Filter and Map without Reduce Filter and Map]]></title>
            <link>https://codeburst.io/reduce-filter-and-map-without-reduce-filter-and-map-787c21671c95?source=rss-3e4d1abc12b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/787c21671c95</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Gustaf Holm]]></dc:creator>
            <pubDate>Mon, 19 Jun 2017 07:58:23 GMT</pubDate>
            <atom:updated>2017-06-19T21:58:33.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NaEBuzve5rTatFt4WlQ0hg.gif" /></figure><h4>Write your own Reduce, Filter and Map without using the built in reduce() filter() and map().</h4><p>A good way to understand what’s going on inside the functional programming must-know-functions is to rewrite them. So as a personal refresher I thought I would share how I implemented reduce() filter() and map(). Without any of the ES6 stuff. And non of the ES7 stuff either 😏.</p><h3>A Simple Map</h3><p>Then .map() method on Array runs every item in an array through a given callback function and returns a new array with the same length as the one the method called on.</p><p>The simplest version of map() I could think of looks like this.</p><pre>function map(array, cb) {<br>  const result = [];<br>  for (let i = 0; i &lt; array.length; i += 1 {      <br>    result.push(cb(array[i]));<br>  }<br>  return result;<br>}</pre><p>Very straight forward here.</p><ol><li>map() takes an array array and a callback function cb as arguments.</li><li>Declares an empty result array for storing the mapped items.</li><li>Loops all the items in the array.</li><li>Run the callback on the current item cb(array[i]).</li><li>Push the return value of the callback function into result.push(...).</li><li>Return the result when the loop is done.</li></ol><p>Run it</p><pre>map([1, 2, 3, 4, 5], item =&gt; item + 1); // [2, 3, 4, 5, 6]</pre><h3>A Simple Filter</h3><p>The .filter() method on Array also runs every item in a given array against a callback function. However, the callback function should always evaluate to a Boolean. So basically it has to return true or false. The items that pass the callback evaluation are returned in a new array.</p><p>The implementation of filter() is almost the same thing as map() .</p><pre>function filter(array, cb) {<br>  const result = [];<br>  for (let i = 0; i &lt; array.length; i += 1) {<br>    if (cb(array[i])) {<br>      result.push(array[i]);<br>    }<br>  }<br>  return result;<br>}</pre><p>The difference here, in comparison to map() is that the callback function cb has to evaluate to true or false. So inside the for loop, we call our callback with the current array item cb(array[i]) inside the if statement. If it evaluates to true , .push that sucker into the results array. When done, return the result.</p><p>Call it.</p><pre>filter([1, 2, 3, 4, 5], item =&gt; item &gt;= 3); // [3, 4, 5]</pre><h3>And a Simple Reduce</h3><p>The .reduce() method is the Array multi tool and can be used in lots of scenarios. However, the fundamental functionality of reduce() is quite straight forward. The function takes tree arguments. An array to iterate upon. A callback function cb to run every item in the array through and an initialValue which you can think of as the container and the starting point for your callback cb results. If you want a string back pass in an empty string &#39;&#39;, if you want an array pass an empty array [] and so one. Your initialValue dosen’t have to empty though. The type of initialValue is mostly dependent on what result your callback returns.</p><p>Being the multi tool, you might think the implementation is very different from filter() and map(). But it’s not. Along with the array and cb arguments I also pass the initialValue.</p><pre>function reduce(array, cb, initialValue) {<br>  let result = initialValue;<br>  for (let i = 0; i &lt; array.length; i += 1) {<br>    result = cb.call(undefined, result, array[i], i, array);<br>  }<br>  return result;<br>}</pre><p>You’ve probably figured it all out already. But I’ll run through it anyway.</p><ol><li>reduce() takes an array array and a callback function cb. Just like our filter() and map(). It also takes an initialValue, as I wrote, you can think of this as the container you want to receive as the return value of your reduce() . The initialValue is tightly coupled with how your callback cb works.</li><li>Declare a result variable and point it to your initialValue , this is just a reference for readability.</li><li>Loops all the items in the array.</li><li>Inside the loop, assign the return value of your callback to the result . Call the callback and set this to undefined and pass the result the current array item array[i], the loop iterator i and the whole array The last to isn’t really needed in this example but I’ve found it good practice to pass all the values. Since we are reassigning result on every loop iteration it’s crucial that your callback returns the entire result and not just the current item. I’m using .call on the cb function since I want to set this to undefined inside the callback.</li><li>When done, retuuuurn result!</li></ol><p>Here’s how to call it.</p><pre>reduce([1, 2, 3, 4, 5], (result, item) =&gt; {<br>  result.push(item * 2);<br>  return result;<br>}, []); // [ 2, 4, 6, 8, 10 ]</pre><p>And here’s the same call but where I’ve broken out the callback for some clarity.</p><pre>const cb = (result, item) =&gt; {<br>  result.push(item * 2);<br>  return result;<br>};</pre><pre>reduce([1, 2, 3, 4, 5], cb, []); // [ 2, 4, 6, 8, 10 ]</pre><h3>Use Reduce to Create Map and Filter 😲</h3><p>Since reduce() is so flexible, you can use it to create your own map() and filter(). The key is, as you might figured out already, to switch the for loop out and replace it with reduce. Go ahead and try building them yourself before checking them out below .</p><h4>Map with Reduce</h4><pre>function map(array, func) {<br>  return reduce(array, function (result, item) {<br>    result.push(func(item));<br>    return result;<br>  }, []);<br>}</pre><p>I’m sure you can figure out what changed yourself, it works the same as our first map(). But now using reduce() internally. The main difference is that I wrapped a reduce() call inside of a map() function. To state the obvious this is a new map() function. It replaces the one I wrote from scratch above.</p><p>Call it the same way as before.</p><pre>map([1, 2, 3, 4, 5], item =&gt; item + 1) // [ 2, 3, 4, 5, 6 ]</pre><p>Here’s a more modern version with arrow functions, implicit return and .concat().</p><pre>const map = (array, func) =&gt;<br>  reduce(array, (result, item) =&gt;<br>    result.concat(func(item)), []);</pre><h4>Filter with Reduce</h4><pre>function filter(array, func) {<br>  return reduce(array, function (result, item) {<br>    if (func(item)) {<br>      result.push(item);<br>      return result;<br>    }<br>    return result;<br>  }, []);<br>}</pre><p>This one you can figure out yourself, so I’ll leave you to it. It’s kind of the same changes as in the previous map() with reduce(). Also call this the same way as we called our first filter().</p><pre>filter([1, 2, 3, 4, 5], item =&gt; item &gt;= 3); // [ 3, 4, 5 ]</pre><p>And a more modern version of this can look like.</p><pre>const filter = (array, func) =&gt;<br>  reduce(array, (result, item) =&gt;<br>    func(item) ? result.concat(item) : result, []);</pre><h4>Also, a modern version of Reduce</h4><p>The only things I did here was switching the declaration to a functional expression using a arrow function and replaced the for loop with the .forEach() method. Very basic. If you have a awesome version of reduce, put it in the responses.</p><pre>const reduce = (array, cb, initialValue) =&gt; {<br>  let result = initialValue;<br>  array.forEach(item =&gt;<br>    result = cb.call(undefined, result, item, array));<br>  return result;<br>};</pre><p>—</p><p>Hope you learned something. I sure was a good refresher for myself. <br>Take care! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=787c21671c95" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/reduce-filter-and-map-without-reduce-filter-and-map-787c21671c95">Reduce, Filter and Map without Reduce Filter and Map</a> was originally published in <a href="https://codeburst.io">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Text Visualization of Template Areas in CSS Grid]]></title>
            <link>https://medium.com/@primalivet/text-vizualization-grid-template-areas-895b210a3341?source=rss-3e4d1abc12b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/895b210a3341</guid>
            <category><![CDATA[css-grid]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Gustaf Holm]]></dc:creator>
            <pubDate>Thu, 08 Jun 2017 06:41:37 GMT</pubDate>
            <atom:updated>2017-06-08T06:41:37.662Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bNw7GyfqH70z2vndQNnTQ.png" /></figure><h4>A straight forward and awesome way to visualize your grid areas in text.</h4><p>As CSS Grid started to roll out I was eager to play with it and one thing i found really nice was the “visualization” in text when you write out your grid-template-areas . Here’s an example of how the CSS maps really nice with the actual grid through 3 media queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*zJm7NOfa07ifpVRgq-OyZQ.png" /><figcaption>The grid on small screens.</figcaption></figure><h4>Overall grid rulset</h4><p>First of I use some basic CSS rules which looks like this.</p><pre>.grid {<br>  display: grid;<br>  grid-gap: 1.5vw;<br>  min-height: 100vh;<br>  padding: 1.5vw;<br>}</pre><p>It doesn&#39;t do anything special, just turn on the grid. Add some spacing and make sure it’s atleast as high as the viewport.</p><h4>Small Screen</h4><p>Before any media queries, since we’re building mobile first, I add some more rules to the .grid selector.</p><pre>.grid {<br>  ...previous rules...<br>  grid-template-columns: repeat(2, 1fr);<br>  grid-template-rows: 50vh 30vh repeat(7, minmax(20vh, 1fr));</pre><p>The first rule grid-template-columns: repeat(2, 1fr); adds 5 columns of equal with. I’m using 1fr instead of % or any other value since it’s doing calculations for grid-gap and padding right out of the box.</p><p>Second rule tells the grid how many rows there’s going to be. This one is pretty straight forward.</p><h4>Small Screen Template Areas</h4><p>Here comes the nice part! See how the rules below 👇 matches the boxes (!) on the screenshot to the left 👈 ( above ☝ on small screens). ️</p><pre>.grid {<br>  grid-template-areas:<br>    &quot;hero   hero&quot;<br>    &quot;big1   big1&quot;<br>    &quot;med1   med1&quot;<br>    &quot;med2   med2&quot;<br>    &quot;small1 small2&quot;<br>    &quot;small3 small4&quot;<br>    &quot;small5 small6&quot;<br>    &quot;small7 small8&quot;<br>    &quot;small9 small10&quot;;<br>}</pre><h4>Medium Screen Template Areas</h4><p>As the screen grows we add a media query with new rules for columns and rows as well as template areas.</p><pre><a href="http://twitter.com/media">@media</a> screen and (min-width: 750px) {<br>  .grid {<br>    grid-template-columns: repeat(5, 1fr);<br>    grid-template-rows: repeat(5, 25vh);<br>    grid-template-areas:<br>      &quot;hero   hero   hero   med1   med1&quot;<br>      &quot;hero   hero   hero   med2   med2&quot;<br>      &quot;big1   big1   big1   big1   big1&quot;<br>      &quot;small1 small2 small3 small4 small5&quot;<br>      &quot;small6 small7 small8 small9 small10&quot;;<br>  }<br>}</pre><p>Really simple, bump up the columns to 5 of equal width and make 5 rows with a height of 25% of the viewport height. So now we get this bad boy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VUh88dPOMr2APS_gSDJsyg.png" /><figcaption>The grid on medium screens.</figcaption></figure><h4>Bigger Screen Template Areas</h4><p>From 1400 pixels we get lots of space to bump up the grid to something special. Let’s add some rules for that.</p><pre><a href="http://twitter.com/media">@media</a> screen and (min-width: 1400px) {<br>  .grid {<br>    grid-template-columns: repeat(6, 1fr);<br>    grid-template-rows: auto;<br>    grid-template-areas:<br>    &quot;small1 hero   hero hero med1   med1&quot;<br>    &quot;small2 hero   hero hero med2   med2&quot;<br>    &quot;small3 small5 big1 big1 small7 small8&quot;<br>    &quot;small4 small6 big1 big1 small9 small10&quot;;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4htpP_A3PU2xJ4TXwUv6eQ.png" /><figcaption>The grid on big screens.</figcaption></figure><p>Here the mapping of the rules in CSS and the grid on the screenshot 👆 really maps out nicely 😍.</p><h4>The rest of the CSS and HTML</h4><p>Below our previous grid rules and media queries we add some more CSS to be able to put each HTML element in their respective grid-template-areas section.</p><pre>.grid .item:nth-child(1)  { grid-area: hero; }<br>.grid .item:nth-child(2)  { grid-area: big1; }<br>.grid .item:nth-child(3)  { grid-area: med1; }<br>.grid .item:nth-child(4)  { grid-area: med2; }<br>.grid .item:nth-child(5)  { grid-area: small1; }<br>.grid .item:nth-child(6)  { grid-area: small2; }<br>.grid .item:nth-child(7)  { grid-area: small3; }<br>.grid .item:nth-child(8)  { grid-area: small4; }<br>.grid .item:nth-child(9)  { grid-area: small5; }<br>.grid .item:nth-child(10) { grid-area: small6; }<br>.grid .item:nth-child(11) { grid-area: small7; }<br>.grid .item:nth-child(12) { grid-area: small8; }<br>.grid .item:nth-child(13) { grid-area: small9; }<br>.grid .item:nth-child(14) { grid-area: small10; }</pre><p>And the HTML for that looks like this. Very basic 😎.</p><pre>&lt;div class=&quot;grid &quot;&gt;<br>  ...<br>  &lt;div class=&quot;item&quot;&gt;<br>    ...<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>I’ve published <a href="https://codepen.io/primalivet/pen/ryjKmV">all code for this at codepen.io</a> which also include a flexbox fallback.</p><p>That’s all 👋.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=895b210a3341" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>