<?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 Aidan Breen on Medium]]></title>
        <description><![CDATA[Stories by Aidan Breen on Medium]]></description>
        <link>https://medium.com/@aidobreen?source=rss-ecef87284345------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2LYVFYOOK_9qB-eFwMMo5A.jpeg</url>
            <title>Stories by Aidan Breen on Medium</title>
            <link>https://medium.com/@aidobreen?source=rss-ecef87284345------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:06:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aidobreen/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[The Case for Self Hosting Your Blog]]></title>
            <link>https://medium.com/@aidobreen/the-case-for-self-hosting-your-blog-99ca0bb40a26?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/99ca0bb40a26</guid>
            <category><![CDATA[blogging]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Tue, 26 Feb 2019 14:16:00 GMT</pubDate>
            <atom:updated>2019-02-26T14:16:00.897Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>We are currently witnessing an internet paradigm shift — in reverse.</blockquote><h3>In The Beginning</h3><p>Once upon a time in the heyday of <a href="https://en.wikipedia.org/wiki/Chain_letter">chain mail</a>, <a href="https://en.wikipedia.org/wiki/RSS">RSS</a> and <a href="https://en.wikipedia.org/wiki/Webring">web rings</a>, before bloggers were bloggers, when people hosted everything on their own servers, content was king.</p><p>The internet was weird and wonderful and useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*3KZHz8itLHM4UWpU.gif" /></figure><p>Then we all collectively [<a href="https://blog.aidanbreen.com/case-for-self-hosting/#fn-1">1</a>] decided that owning our own content was for losers and posting on a centralized system with likes, shares, and reblogs was clearly the superior approach.</p><h3>Continued…</h3><p><a href="https://blog.aidanbreen.com/case-for-self-hosting/">Read the rest over at my self hosted blog…</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99ca0bb40a26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vivisection of OpenTable widget.]]></title>
            <link>https://medium.datadriveninvestor.com/vivisection-of-opentable-widget-ea0618d4531c?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea0618d4531c</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Wed, 06 Feb 2019 14:01:01 GMT</pubDate>
            <atom:updated>2019-02-07T14:53:28.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="http://www.track.datadriveninvestor.com/1B9E"><img alt="" src="https://cdn-images-1.medium.com/max/700/0*XNyHyHybUoHuDB22" /></a></figure><p>You may be familiar with OpenTable, a service built around restaurant bookings. One of their main features is an embeddable widget that restaurants can insert in their website to let patrons reserve a table. Here’s what it looks like in the wild:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ek_yEFfo3gvm09rhiyWMQ.png" /><figcaption>OpenTable widget on <a href="http://thehillpub.ie/">http://thehillpub.ie/</a></figcaption></figure><p>This widget was generated by the OpenTable widget builder page like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQIpXQWtbMwltiw6u4wc1A.png" /><figcaption>Try it yourself at: <a href="https://www.opentable.com/widget/reservation/preview?rid=412810&amp;language=en-US&amp;domainId=1&amp;countryCode=US">opentable</a></figcaption></figure><p>As you can see, we can change a few settings and then just copy the code into our own website. Pretty handy, but how does it work?</p><h3>The loading script</h3><p>The script we copy is simply a &lt;script/&gt; tag, which is used to load javascript. We can simply copy the URL into a browser window to see the code that would be loaded:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwEf-CGvrQyfNv6Q1jD7dQ.png" /></figure><p>Yikes. It’s obviously been minified (as you would expect) but hope is not lost. Let’s copy this into a text editor and run some auto formatting:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqtOF0C94zaGtTbt8eh--w.png" /></figure><p>Ok, that looks a bit more approachable. For reference, I’m using the Atom text editor with Atom-beautify for auto formatting.</p><h4>First impressions</h4><p>First thing to note here is the outer function syntax:</p><pre>! function(i, n) {<br>  ...<br>}(window, document);</pre><p>This is a <strong>self-executing anonymous function.</strong> That is, the function is called as soon as it is loaded (“self executing”), it doesn’t have a name or a variable reference (“anonymous”). This is a common approach for plugins and widgets, and was particularly common for jQuery plugins. In my experience, I have seen this mostly using the double bracket pair syntax: (function(){})() but this does the same thing.</p><p>The ! is simply a unary operation (a logical “not”) that forces javascript to execute the function. If the output of the function was stored in a variable, it would be negated, but since the function doesn’t return anything, and the result isn’t stored or used anywhere, it has no effect.</p><p>Next thing to note is that window and document are passed into the function and will be referenced by i and n respectively inside the function.</p><p>Let’s find and replace the occurrences of i and n for the sake of clarity…</p><h4>Defaults and the Comma Operator</h4><p>Looking at the internals of the function, we see that the widget starts by assigning <em>stuff</em> to the window, but it does this is a fairly interesting way, first by checking for an existing window.OT value using || , and if none exists (ie. if window.OT is undefined), the code after the ||is executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ngiHpKvGhxxbrFDLb_3hBQ.png" /></figure><p><strong><em>Why would we bother checking for an existing window.OT value?</em></strong><em> I assume this is to handle a website embedding the code in more than one place. This way we only ever execute the code after the </em><em>|| once.</em></p><p>So, after the ||…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvBl7IdqT9WtNmkdOh_NUw.png" /><figcaption>Note: I have “folded” each function to highlight the comma operator syntax.</figcaption></figure><p>We see an empty object followed by a comma…weird.</p><p>Usually we would expect a comma to be inside a function declaration, an array or an object, right? In this case, the comma is used as an <strong>operator.</strong></p><blockquote>The<strong> comma operator</strong> evaluates each of its operands (from left to right) and returns the value of the last operand. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator">MDN</a></blockquote><p>Based on that description, the empty object is “evaluated” <em>[see note below]</em>, then a function is declared and assigned to OT.createNS <em>[note 2], </em>this function is then called a few times.</p><p><strong><em>Note: Why the empty object? If each step is evaluated and only the last value is returned, what use is the empty object?</em></strong><em> <br>By playing around a bit, I have discovered that the empty object is necessary to avoid an error when assigning the </em><em>OT.createNS function right after the </em><em>|| operator. Specifically: “Uncaught ReferenceError: Invalid left-hand side in assignment”.</em></p><h4>The CreateNS function</h4><p>This function gets called a few times, and as far as I can tell, it is simply used to set up the OT object with nested attributes. I think NS might stand for Name Space, but that’s a guess.</p><p>In short, it converts the string “OT.something.else.entirely” to an object.</p><p>It’s fairly straightforward, with the only interesting bit being the use of the <strong>void</strong> operator:</p><blockquote>The <strong>void operator</strong> evaluates the given <em>expression</em> and then returns undefined. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void">MSDN</a></blockquote><h4>The OT functions</h4><p>The next few lines use the createNS function to ensure the OT object has an attribute of a certain name, and then assigns a function to each of these attributes. The functions are self explanatory:</p><p>createScriptTag, createCssTag, createOcTag, createIFrameTag, loadJQuery</p><h4>The Modal</h4><p>All of this extra work is building up to being able to inject a “modal” into the host page. The modal in question appears when you click the “find a table” button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wIrfsK6CSN3RJOpBHcBTkQ.png" /></figure><p>Modals are a fairly challenging (and controversial!) UI element. They have to sit over everything in your page, position themselves in the center of the screen, and go away when you need them to.</p><p>I try to avoid them if possible, as they also lead to accessibility issues and pose a challenge for screen readers.</p><p>All this leads to complex CSS and JS, which isn’t apparent in the code that we copied…so where is it?</p><p>Going even further down this rabbit hole, we can inspect the modal and discover that the contents actually come from an i-frame. That means the UI and elements are really a completely separate web page, loaded from a different server, simply placed over the host website.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgL-0WiGGUEq9mxJAr4VoA.png" /></figure><p>The code we are vivisecting really only builds the src for the iframe, passing in the details of the specific restaurant.</p><p>From here, it is quite straightforward and well beyond the scope of this post. The modal i-frame is a fully functional web application (a react app if the class name “react-root” is to be believed).</p><h3>Conclusion</h3><p>We have seen some interesting patterns here — most of them (the comma operator usage for example) are fairly specific and probably the result of a preprocessor trying to produce a smaller JS. I’m not too sure what, how or why, but hopefully somebody can comment with an explanation.</p><p>The whole thing, however, boils down to a fairly simple approach:</p><ol><li>Get the user to copy a &lt;Script&gt; tag in the host page.</li><li>Use a self executing anonymous function in the &lt;script&gt; to…</li><li>Insert an &lt;i-frame&gt; tag close to the script tag, and…</li><li>Load your widget from your own server.</li></ol><p>Thanks for reading!</p><p>I’m <a href="https://twitter.com/aidanbreen">Aidan Breen</a>, and I run a <a href="http://apbsoftware.ie/">software consultancy</a> in Dublin, Ireland. If you enjoyed this post, consider following me on <a href="https://twitter.com/aidanbreen">twitter</a>, or signup to my <a href="https://apbsoftwareandhardware.us3.list-manage.com/subscribe?u=bd4ace12c9503b0fb9dde0282&amp;id=6081e1a8d6">personal mailing list</a> for less than monthly updates.</p><h4>Related Stories from DDI:</h4><p><a href="https://www.datadriveninvestor.com/2019/01/23/which-is-more-promising-data-science-or-software-engineering/">Which is More Promising: Data Science or Software Engineering? | Data Driven Investor</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fb2a0d6%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2Fb2a0d6%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href">https://medium.com/media/0707f5c806284d01a4a13c7b13a91ce3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea0618d4531c" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/vivisection-of-opentable-widget-ea0618d4531c">Vivisection of OpenTable widget.</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applications as Configurations]]></title>
            <link>https://levelup.gitconnected.com/applications-as-configurations-5d43e3fec890?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d43e3fec890</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 11:42:07 GMT</pubDate>
            <atom:updated>2019-01-30T22:32:58.345Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a thought:</p><blockquote>“Most software applications consist of the same basic functions in different configurations”.</blockquote><p>Let’s play with that. Imagine a super-high-level language that could describe a software application tersely, but still capture the usefulness of the application.</p><h4>✏️ Our app</h4><pre><strong>Example 1</strong><br>App: Twitter<br>  Allow user to: login<br>  Allow user to: send a tweet<br>  Allow user to: follow another user<br>  Allow user to: view a timeline of tweets</pre><pre><a href="https://gist.github.com/aido179/1734bb23182d801f4db3b3e694d54a63">(further examples here)</a></pre><ul><li>Our app needs a name, we’ll use Twitter as an example. <br><em>I’ve made other examples </em><a href="https://gist.github.com/aido179/1734bb23182d801f4db3b3e694d54a63"><em>here</em></a><em> too.</em></li><li>login is pretty self explanatory and so common that we can assume it’s baked into the language. login becomes library.login indicating we will use provided library behaviour and not a custom implementation.</li><li>send a tweet is a unique instance of a very common action: take some user input (data: text, image, video, audio etc) and store it somewhere (write), so it can be returned (read) later. We can specify all that in more detail later. For now, let’s imagine send a tweet just references further configuration somewhere else, and becomes custom.tweet</li><li>follow another user again, a unique name for a common action: make a link, connection or relationship between two things, in this case, users of our app. In the case of twitter, the follower-to-followed relationship is <strong>many-to-one</strong>. The Facebook friend-to-friend relationship is <strong>one-to-one. </strong>On reddit, user-to-subreddit subscriptions are<strong> one-to-many. <br></strong>follow another user becomes custom.follow</li><li>view a timeline of tweets is a read action. It’s going to get some set of things, arrange them somehow and display them to the user. It will probably have nested actions, like <em>liking</em>, <em>retweeting</em> and <em>replying</em> but we’ll handle that later. It becomes custom.timeline</li></ul><p>Ok, let’s iterate.</p><pre><strong>Example 2</strong><br>App: Twitter<br>  Allow user to: library.login<br>  Allow user to: custom.tweet<br>  Allow user to: custom.follow<br>  Allow user to: custom.timeline</pre><p>Each allow user to line corresponds to a function of the app, but may include multiple UI components. Library.login will obviously require a login page, a logout button somewhere else and other elements to update passwords and other information. custom.follow might appear in multiple places throughout the app.</p><h4>🌇 Structure and views</h4><p>It probably makes sense then to define the structure of the app separately, but with reference to the previously defined actions.</p><pre><strong>Example 3</strong><br>App: Twitter<br>  Actions:<br>    #Allow the user do these...<br>    - library.login<br>    - custom.tweet<br>    - custom.follow<br>    - custom.timeline<br>  Views:<br>    # Allow the user to view these <br>    - library.landingPage<br>    - custom.home<br>    - custom.profile</pre><p>Here I’ve split the app into Actions and Views. We’ll consider the first view in the list (library.landingPage) to be the default or index. Again, using library means it’s built in. Allowing us to use default boilerplate like this should help speed up development. We can always come back later and use a custom view instead.</p><h4>🔗 Views and Actions</h4><p>Mapping actions to parts of our application structure is not trivial. Some pages will have specific actions, and some actions will be reused in many views. Each view should define exactly the actions it needs.</p><pre><strong>Example 4</strong><br>App: Twitter<br>  Actions:<br>    #Allow the user do these...<br>    - library.login<br>    - custom.tweet<br>    - custom.follow<br>    - custom.timeline<br>  Views:<br>    # Allow the user to view these <br>    - library.landingPage<br>        - library.login<br>    - custom.home<br>        - library.login.isUserloggedIn<br>        - custom.tweet<br>        - custom.timeline<br>    - custom.profile<br>        - library.login.isUserloggedIn<br>        - custom.follow</pre><p>Now views have specific actions. We can now have functionality, with the added bonus that is totally clear what happens in each view.</p><p>Notice how library.login is used in each view. The library.login action is like a package with many nested functions. We should be able to use specific parts of an action like this — where we don’t need to let the user login on each page, but only check that they are logged in.</p><h3>🗣️ Discussion</h3><p>It is conceivable that a configuration like this could be used to generate all the necessary boilerplate for an application. At this point, the application could be generated for any platform too.</p><p>None of this is necessarily new. <a href="https://www.meteor.com/">Meteor</a> provides default app generation, boilerplate login functionality, and client-server comms. <a href="https://reactjs.org/">React</a> has <a href="https://github.com/facebook/create-react-app">create-react-app</a> which…creates a React app for you. The <a href="https://cli.vuejs.org/guide/creating-a-project.html">Vue CLI</a> <em>create</em> command will scaffold your app. In fact, tools like <a href="https://yeoman.io/">Yeoman</a> literally allows you to define a ‘generator’ and spit out a scaffolded application. Further, <a href="https://facebook.github.io/react-native/">React Native</a> takes a JavaScript project (basically a highly featured configuration) and generates native applications, similar to<a href="https://cordova.apache.org/"> Cordova</a>.</p><p>Code generation is not new. So what’s different here?</p><p>In the case of <em>Yeoman</em>, <em>create-react-app</em> and the VUE <em>create</em> command, once the scaffolding is generated, it’s all up to you. You are left with standard application code and development continues as normal. What I propose here is a tight coupling where <strong>the configuration becomes the application</strong>, not just a blueprint. That is, if you change the configuration at any time, the code will be updated to reflect that change. Write code that conflicts with the configuration, you get errors.</p><p><strong>A developer should be able to look at the configuration and know that the application strictly conforms to that definition.</strong></p><p>In the case of Meteor, with it’s highly functional login boilerplate and client-server comms (pub/sub), (which I think is wonderful, by the way) this goes a step further. User authentication and login is not a convenient package that happens to work quite well — it should be baked in to the very core of the system. With Meteor, the developer still needs to write templates that show/hide content or routes based on the users logged in state. This is silly. At best, it is inconvenient and leads to template overhead. At worst, it is a security risk when, though accident or inexperience, a developer does not handle authentication correctly.</p><p><strong>It should be impossible to create insecure apps!</strong></p><p>When a view is defined like this:</p><pre>...<br>Views:<br>    - custom.home<br>        - library.login.isUserloggedIn<br>        ...</pre><p>There should be nothing else to do. If the user isn’t properly authenticated, it isn’t accessible. That’s it. No fiddling with client side routers, entry events, or app-wide templates or anything else. The config is God. The config wins.</p><p>Finally, (for now) there are massive benefits when it comes to deployment and maintenance. Deterministic configurations should provide reliable deployments, and make dependency management easy. Imagine an app you built 5 years ago using library.login: you should be able to trust that a new deployment will include up-to-date authentication code — because your app will be generated using the standard configuration, it is always backwards compatible. Even if massive high level changes need to be made, as long as you use library.login.isUserloggedIn, your view will be protected on a higher level by the generated app code.</p><h4>🎬 Conclusion</h4><p>I know I am being incredibly idealistic here. I’m certain that there are edge cases and complications that make this completely impractical for some purposes. But this isn’t supposed to be a panacea. It’s supposed to work for the 90% of applications that need to make CRUD operations protected by user authentication.</p><p>But it’s fun to dream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*yfvCORQgYCtThAaG4Ecr2g.jpeg" /><figcaption>This is a fish.</figcaption></figure><p>I’m <a href="https://twitter.com/aidanbreen">Aidan Breen</a>, and I run a <a href="http://apbsoftware.ie/">software consultancy</a> in Dublin, Ireland. If you enjoyed this post, consider following me on <a href="https://twitter.com/aidanbreen">twitter</a>, or signup to my <a href="https://apbsoftwareandhardware.us3.list-manage.com/subscribe?u=bd4ace12c9503b0fb9dde0282&amp;id=6081e1a8d6">personal mailing list</a> for less than monthly updates.</p><figure><a href="https://levelup.gitconnected.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6CoI_MRyZ1JInNPsBSHtA.png" /></a></figure><p><a href="https://gitconnected.com/learn">Learn to Code - Find Programming Tutorials | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d43e3fec890" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/applications-as-configurations-5d43e3fec890">Applications as Configurations</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mapping out my side-projects]]></title>
            <link>https://medium.com/@aidobreen/mapping-out-my-side-projects-8f1ae3132194?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f1ae3132194</guid>
            <category><![CDATA[side-project]]></category>
            <category><![CDATA[music]]></category>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Fri, 07 Dec 2018 16:46:22 GMT</pubDate>
            <atom:updated>2018-12-10T11:32:44.640Z</atom:updated>
            <content:encoded><![CDATA[<p>It turns out there’s a lot to learn by examining the cadence and variety of your side-projects…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45cnPgUTLGLUIYjdATAWXA.png" /><figcaption>Figure 1: Projects over time. Check out the original <a href="https://docs.google.com/spreadsheets/d/1SAovFyvcWUSptHiIF_4OrJ-IUCxL6fPWg1O7IWKYkrI/edit?usp=sharing">spreadsheet here</a>.</figcaption></figure><p>I recently defended my PhD and in the process of preparing for the defence, I discovered that an old backup hard-drive was damaged beyond repair. Thankfully I had a further backup, but it got me thinking:</p><blockquote>There’s a lot of stuff here that I probably will never look at again, but it’s important to me that I recognise it’s existence.</blockquote><p>I hope I never have to look back at the PHP I wrote when I was learning, but I spent months cobbling together SQL queries and designing objectively terrible pages, and that process is important, at least to me.</p><p>Then I thought:</p><blockquote>I’ve shared a lot of this stuff over the years, I wonder how many people have seen the stuff I’ve made?</blockquote><p>The projects I could find hard data for include:</p><ul><li>Original Music</li><li>6 Websites</li><li>3 Youtube Channels</li><li>3 Chrome Extensions</li><li>2 SAAS platforms</li><li>A physical product</li><li>and this blog.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PjyowTs74t7JUzWNKKN_ig.png" /><figcaption>Figure 2: Project data. Again, from the original <a href="https://docs.google.com/spreadsheets/d/1SAovFyvcWUSptHiIF_4OrJ-IUCxL6fPWg1O7IWKYkrI/edit?usp=sharing">spreadsheet here</a>. Links included, where possible</figcaption></figure><h3><strong>Findings</strong></h3><p>I decided to go back as far as 2010, around about when I started my undergraduate degree, and when I started creating meaningful things that could be shared on the internet.</p><h4>Relatively steady cadence</h4><p>Figure 1 above shows pretty clearly that from 2012, I tended to start between 2 and 4 projects a year. There are some gaps (June 2015 — August 2016), and some times where I start a few projects close together (Early 2018), but overall, there’s never really a time where I don’t have a project to work on.</p><h4>Blog posts come in spurts</h4><p>The black bordered cells in Figure one indicate that at least 1 blog post was made that month. They tend to happen together, with large gaps in between. Obviously, I’ve begun to write more frequently lately. I think I also tend to write when I’m in need of a quick win: it’s a goal I can achieve in about a day or less and consider complete.</p><h4>Newer projects are less viral</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJyCt8H1o6Ezboi4e1WQNw.png" /><figcaption>Left to right: oldest to newest. We should disregard Medium (this blog) here as new posts are added over time.</figcaption></figure><p>Obviously, older projects are going to have more views, but we would expect the decrease in lifetime views to be somewhat linear. In actual fact, my newer project don’t seem to get anything like the kind of exposure that my older projects got.</p><p>I think this might be due to my focus changing from <strong>viral content </strong>(“<a href="http://blogify.org/">blogify 2</a>” was designed to copy content from reddit and repost the links), to actual <strong>useful tools</strong> (“<a href="http://bluespots.app/">Blue Spots Parking</a>” is an app to help disabled drivers find accessible parking spaces). Making useful tools that also gain viral traction is a sweet spot I have not yet managed to find.</p><p>But perhaps this is also a reflection on how social networks are becoming less effective. Reddit, Facebook and twitter have always been the main way I share my projects.</p><h4>Views are not correlated to revenue.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLEOerLT8Jt0iU1IhdL11Q.png" /><figcaption>These figures include prize money. “Reviewyour.Website”, “The Cub” and “Posture” have not received any prize money.</figcaption></figure><p>It’s safe to say that I won’t be quitting the day job any time soon, but I think making any money at all off a side-project is a massive success regardless of the magnitude. I have three main observations here:</p><ol><li>The project with the most views still made no money. I actually didn’t even put ads on the “Blogify 2” site. I felt it was immoral to profit off it.</li><li>The physical product performed by far the best in terms of dollars-per-view. It was also the most challenging project though and probably took far more effort-per-view than any other project, if you could measure that.</li><li>Music is hard.</li></ol><h3>Conclusion</h3><p>It’s probably about time to start something new. If I want to maximize the views, revenue and longevity, I should probably try to build a physical product that is a useful tool with a viral aspect, which has nothing to do with music.</p><p>Easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Av2mV3UHJ-9cUvRkogf_Q.jpeg" /></figure><p>I’m <a href="https://twitter.com/aidanbreen">Aidan Breen</a>, and I run a <a href="http://apbsoftware.ie/">software consultancy</a> in Dublin, Ireland. If you enjoyed this post, consider following me on <a href="https://twitter.com/aidanbreen">twitter</a>, or signup to my<a href="https://apbsoftwareandhardware.us3.list-manage.com/subscribe?u=bd4ace12c9503b0fb9dde0282&amp;id=6081e1a8d6"> personal mailing list</a> for less than monthly updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f1ae3132194" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero Dependency HTML templating in 12 lines of Javascript.]]></title>
            <link>https://medium.datadriveninvestor.com/zero-dependency-html-templating-in-12-lines-of-javascript-1fc0f6516edf?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fc0f6516edf</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Mon, 12 Nov 2018 12:41:01 GMT</pubDate>
            <atom:updated>2018-11-12T12:41:01.310Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is a piece of code I wrote for a previous blog post about </em><a href="https://medium.com/@aidobreen/how-to-build-a-custom-mocha-reporter-45b098d95ef6"><em>writing a Custom Mocha Reporter.</em></a><em> I wanted to generate HTML output from a template, but I didn’t need much functionality or an extra dependency. Turns out, it’s not that difficult.</em></p><p>Programmatically generating or producing HTML is not rocket science. The typical approach is:</p><ol><li>Build a HTML template close to what you want.</li><li>Identify the variable parts of the template you want to change.</li><li>Write your code to get the replacement parts.</li><li>Use a templating engine to load the HTML and replace the variables with the replacement parts.</li></ol><p>There are loads of templating engines out there. <a href="https://www.npmjs.com/package/mustache">Mustache</a> is one. <a href="http://tryhandlebarsjs.com/">Handlebars</a>, <a href="http://olado.github.io/doT/index.html">doT</a> and <a href="http://ejs.co/">EJS</a> also do the job. They all basically work the same, but they all represent an extra dependency that we don’t need. We’re not doing anything complex here, and I’d rather keep this package with zero dependencies. So build it ourselves.</p><h4>Regular Expressions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*mlI0m2Uwj16gtPQuGm_qug.png" /><figcaption>Artists impression of a lake surrounded by red cabbage and carrots fields.</figcaption></figure><p>Regular expressions (regex) are a <strong>wonderful</strong>, <strong>powerful</strong> and <strong>complex </strong>concept that I wont get into in too much detail. Basically, a regular expression allows you to define an “expression”, or pattern, that can be used to find specific sequences in a body of text. A common use of regex is to find a substring, and replace it. Regex can also be used to validate data, ensuring it conforms to some structure (ie. phone numbers contain only numbers and are 10 digits long)</p><h4>Replacing a String.</h4><p>Regex are not unique to Javascript, and even within JS, there are multiple ways to utilise them. In our case, we’ll use the string.replace() method. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">(full documentation here)</a></p><pre>str.replace(regexp|substr, newSubstr|function)</pre><p>We’re going to take a string called template and find every occurrence of words surrounded by double squiggly brackets like so: {{word}} . Then we’re going to replace that word with a value we have generated — in the case of the Mocha reporter, we used the output of our tests, but it can be anything at all.</p><p><strong>For example</strong>, say we have calculated the percent of tests that ran successfully as: run_percent , and in our template we have written {{run_percent}} . We could write: template.replace(/{{run_precent}}/g, run_percent)</p><blockquote>The<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Creating_a_regular_expression"> regex literal </a>is surrounded by forward slashes. The ‘g’ means <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global">search globally.</a></blockquote><h4>Replacing Multiple Strings</h4><p>But we can do better. We can find <strong>any word </strong>surrounded by squigglies with the following regex: /{{.*?}}/g</p><blockquote><em>.</em> means any character except a newline. <br><em>*</em> means match the previous thing 0 or more times.<br><em>?</em> means make the previous thing ‘non-greedy’ — ie. The shortest possible match.</blockquote><p>Finally, we’re not just going to replace every word in squigglies with just one value. If we pass a function as the second parameter to replace(), we can be much smarter…</p><pre>let newContent = template.replace(/{{.*?}}/g, function(match){<br>  <strong>return</strong> replacements[match]<br>})</pre><p>Here,Match is the word that is found by the regex. replacements is an object with keys for each of our template variables (the squigglies), and values for what we want to replace them with. Here’s an example:</p><pre><strong>// Example of replacements object</strong><br>{<br>      &quot;{{lastrun_date}}&quot;: new Date(),<br>      &quot;{{run_percent}}&quot;: run_percent,<br>      &quot;{{run_numerator}}&quot;: sum,<br>      &quot;{{run_denominator}}&quot;: total<br>}</pre><p>Wrapping it all up with the file reading/writing code in a nice little function (called updateBillboard in our reporter) and we have our templating engine in <a href="https://github.com/aido179/apb-mocha-reporter/blob/140e22119925142dd2d09bd22dd62764bbd46799/src/apbmochareporter.js#L91">12 lines of Javascript</a>:</p><pre>function updateBillboard(replacements){  <br>  content = fs.readFileSync(`template.html`, {encoding:&#39;utf8&#39;})<br>  let newContent = content.replace(/{{.*?}}/g, <br>    function(match){<br>      return replacements[match]<br>    })<br>  let output= `/output.html`<br>  if (!fs.existsSync(output_dir)){<br>    fs.mkdirSync(output_dir);<br>  }<br>  fs.writeFileSync(output, newContent)<br>  return output<br>}</pre><h3>Conclusion</h3><p>Obviously, this isn’t going to be suitable for anything with complex templating needs. But, in my opinion, installing a whole extra package just to replace a few values in a file is overkill.</p><p>I’m <a href="https://twitter.com/aidanbreen">Aidan Breen</a>, and I run a <a href="http://apbsoftware.ie/">software consultancy</a> in Dublin, Ireland. If you enjoyed this post, consider following me on <a href="https://twitter.com/aidanbreen">twitter</a>, or signup to my <a href="http://Ok, screw it. Let&#39;s give this a go and see what happens:  http://eepurl.com/dMEsHg">personal mailing list</a> for less than monthly updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fc0f6516edf" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/zero-dependency-html-templating-in-12-lines-of-javascript-1fc0f6516edf">Zero Dependency HTML templating in 12 lines of Javascript.</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to: Build a Custom Mocha Reporter]]></title>
            <link>https://medium.com/@aidobreen/how-to-build-a-custom-mocha-reporter-45b098d95ef6?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/45b098d95ef6</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[mocha]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 12:46:49 GMT</pubDate>
            <atom:updated>2018-12-07T16:45:01.099Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build a Zero Dependency Custom Mocha Reporter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*0-PfwGsz2EROLBFmM3VGUA.png" /><figcaption>Get it? Mocha / reporter? No? Nevermind.</figcaption></figure><p><em>Warning: This article is basically tech arts-and-crafts.</em></p><p>I want to display a screen in the office showing the latest unit test results, like a notice board, so the whole team can see the test status —and we wont miss failing tests.</p><p>We use <a href="https://mochajs.org/">Mocha</a> to run unit tests in Node (<a href="https://nodejs.org/">nodejs</a>). Jenkins watches our git repo and runs tests when we push new code.</p><p>The final product (<a href="https://github.com/aido179/apb-mocha-reporter">github</a>, and <a href="https://www.npmjs.com/package/apb-mocha-reporter">npm package</a>) is viewed in a browser, refreshed automatically and looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Do4oSIUH9A9W9uPL9viUoQ.png" /></figure><h3>Introduction</h3><p>With <a href="https://mochajs.org/">M</a>ocha, we can run $ mocha ./src/**/*.test.js to produce a console report that looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*jXQNdfr9bl1gRbxOPuwz7Q.png" /><figcaption>Borrowed from the mochajs website. Our real test suite is larger. I promise.</figcaption></figure><p>But did you know you can output test results in any format you like using a <strong>reporter</strong>? Mocha even provides <a href="https://mochajs.org/#reporters">a bunch of example / fun reporters build in.</a></p><p>We can use:</p><pre>mocha ./src/**/*.test.js --reporter &lt;reporterName&gt;</pre><p>the --reporter flag allows us to use a custom reporter.</p><h3>Single File or Package?</h3><p>Writing your own custom reporter can be as simple as created a single Javascript file in an existing project, and referencing it using the -reporter flag.</p><p>To demonstrate, Mocha provides <a href="https://github.com/mochajs/mocha/wiki/Third-party-reporters">example custom reporter code</a>, which we can save in the root of our project and reference like: mocha ./src/**/*.test.js -reporter reporter.js</p><p>Alternatively, you may want to wrap your reporter up in a package to use elsewhere. This is a bit beyond the scope of this article, however, I should mention that <a href="https://github.com/mochajs/mocha/issues/3530#issue-372977357">I have had issues with mocha not recognising local packages</a>.</p><h3>Getting started</h3><p>The <a href="https://github.com/mochajs/mocha/wiki/Third-party-reporters">example code</a> actually works rather well and is very straightforward. We simply export a single function (or reporter) which is passed a “runner” object providing some events we can hook into.</p><pre><strong># Example code from Mocha - we just export this one function</strong><br>module.exports = MyReporter;<br>function MyReporter(runner) {<br>  ...<br>}</pre><p>Our custom reporter is going to take the following format:</p><pre>function MyReporter(runner) {<br>  // 1. Store intermediate values <br>  //    to be inserted into the HTML template later<br>  <br>  // 2. Update these values when tests run, pass or fail.<br>  <br>  // 3. When the runner ends, update the HTML file<br>}</pre><p>The final result can be seen in <a href="https://github.com/aido179/apb-mocha-reporter/blob/140e22119925142dd2d09bd22dd62764bbd46799/src/apbmochareporter.js">apb-mocha-reporter/src/apbmochareporter.js</a> on github.</p><h4>Calculating the values we want to display</h4><p>Based on the example code, I began by writing hooks for the ‘pass’ and ‘fail’ events, summing up the number of tests in each category to get the values we will insert into our HTML. <a href="https://github.com/mochajs/mocha/issues/3530#issuecomment-432596000">I later discovered</a> that these values are already tallied up for me by runner.stats so I’ll use that instead.</p><p>However, I also want to output detailed test results in JSON format, so I still need to write some hooks. I start by declaring some function scoped arrays to hold the test results, then I push into those arrays whenever an event hook fires. Here’s an example for a test ‘pass’ hook:</p><pre>var json_passes = [];<br>runner.on(&#39;pass&#39;, function(test){<br>    json_passes.push(test);<br>    update() <strong>// print to the console.</strong><br>});</pre><p>Now we have total control of the output — Let’s format it as HTML.</p><h3>HTML Output — template engine in 12 lines of code.</h3><p>Programmatically generating or producing HTML is not rocket science. The typical approach is:</p><ol><li>Build a HTML template close to what you want.</li><li>Identify the variable parts of the template you want to change.</li><li>Write your code to get the replacement parts.</li><li>Use a templating engine to load the HTML and replace the variables with the replacement parts.</li></ol><p>There are loads of templating engines out there. <a href="https://www.npmjs.com/package/mustache">Mustache</a> is one. <a href="http://tryhandlebarsjs.com/">Handlebars</a>, <a href="http://olado.github.io/doT/index.html">doT</a> and <a href="http://ejs.co/">EJS</a> also do the job. They all basically work the same, but they all represent an extra dependency that we don’t need. We’re not doing anything complex here, and I’d rather keep this package with zero dependencies. So build it ourselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*mlI0m2Uwj16gtPQuGm_qug.png" /><figcaption>Artists impression of a lake surrounded by red cabbage and carrots fields.</figcaption></figure><h4>Regex Replacement</h4><p>Regular expressions (regex) are a <strong>wonderful</strong>, <strong>powerful</strong> and <strong>complex</strong> concept that I wont get into in too much detail. Regex are not unique to Javascript, and even within JS, there are multiple ways to utilise them. In our case, we’ll use the string.replace() method. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">(full documentation here)</a></p><pre>str.replace(regexp|substr, newSubstr|function)</pre><p>We’re going to take a string called template and find every occurrence of words surrounded by double squiggly brackets like so: {{word}} . Then we’re going to replace that word with a value we have generated — in this case, the output of our test.</p><p><strong>For example</strong>, say we have calculated the percent of tests that ran successfully as: run_percent , and in our template we have written {{run_percent}} . We could write: template.replace(/{{run_precent}}/g, run_percent)</p><blockquote>The<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Creating_a_regular_expression"> regex literal </a>is surrounded by forward slashes. The ‘g’ means <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global">search globally.</a></blockquote><p>But we can do better. We can find <strong>any word </strong>surrounded by squigglies with the following regex: /{{.*?}}/g</p><blockquote>. means any character except a newline. <br>* means match the previous thing 0 or more times.<br>? means make the previous thing ‘non-greedy’ — ie. The shortest possible match.</blockquote><p>Finally, we’re not just going to replace every work in squigglies with just one value. If we pass a function as the second parameter to replace(), we can be much smarter…</p><pre>let newContent = template.replace(/{{.*?}}/g, function(match){<br>  <strong>return</strong> replacements[match]<br>})</pre><p>Here,Match is the word that is found by the regex. replacements is an object with keys for each of our template variables (the squigglies), and values for what we want to replace them with. Here’s an example:</p><pre><strong>// Example of replacements object</strong><br>{<br>      &quot;{{lastrun_date}}&quot;: new Date(),<br>      &quot;{{run_percent}}&quot;: run_percent,<br>      &quot;{{run_numerator}}&quot;: sum,<br>      &quot;{{run_denominator}}&quot;: total<br>}</pre><p>We wrap it all up with the file reading/writing code in a nice little function called updateBillboard and we have our templating engine in <a href="https://github.com/aido179/apb-mocha-reporter/blob/140e22119925142dd2d09bd22dd62764bbd46799/src/apbmochareporter.js#L91">12 lines of Javascript.</a></p><p>Finally, the updateBillboard function is called from the runners end event.</p><h3>Handling Command Line Arguments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6hO-s8vhvCc_BOmiDX7vA.png" /><figcaption>True story: I posted this image to /r/programmerhumor and it was removed as a violation of Rule #3: No low quality, low effort posts.</figcaption></figure><p>I want the user to be able to control how the reporter works. The most simple example is to prevent console output.</p><p>Mocha provides a basic way to pass command line arguments to the reporter through the —-reporter-options flag. This option isn’t particularly well documented — the main documentation only says:</p><pre>Usage: mocha [debug] [options] [files]<br>Options:<br>...<br>-O, --reporter-options &lt;k=v,k2=v2,...&gt;  reporter-specific options<br>...</pre><p>This means we can use either -O or —- reporter-options followed by a comma separated list of options (no spaces!). Each option may have a value, provided after an equals sign. This value is optional.</p><p>What <strong><em>isn’t </em></strong>described anywhere (but the example code) is how the reporter-options are passed on the reporter:</p><pre>function MyReporter(runner, options) {<br>  const SILENT = options.reporterOptions.silent<br>  ...<br>}</pre><p>A second options parameter is passed to the reporter function as an object containing a reporterOptions object, that contains each option and its value.<br><strong>Example:</strong></p><pre><strong>// Test command</strong><br>mocha ./**.test.js --reporter MyReporter --reporter-options silent,savejson=example</pre><p>Gives us the following in our custom reporter:</p><pre><strong>// console.log(options) inside MyReporter()</strong><br>{ <br>  reporterOptions: { silent: true, savejson: &#39;example&#39; },<br>  globals: [],<br>  files: [] <br>}</pre><p>If no value is provided (like for silent ) the default is the boolean true.</p><h4>Using the command line arg to prevent logs</h4><p>To control when logs happen, we’ll store the value of the silent option and write a simple logging function to check it:</p><pre>const SILENT = options.reporterOptions.silent<br>function write(str){<br>  if(!SILENT) process.stdout.write(str);<br>}</pre><p>Now we replace all logs with write() and when the silent option is passed, nothing happens!</p><blockquote>I’m using process.stdout.write(str); so I can manually handle new lines (\n) vs carriage returns (\r) to overwrite previous output.</blockquote><h3>Conclusion</h3><p>And Voila!</p><p>Our test status is displayed somewhere in a typically dull office environment. Fake plant and all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tHPg4UWZkD8ChJFZwUrX8Q.jpeg" /></figure><p><em>I searched briefly for existing jenkins plugins / mocha reporters but didn’t find anything 100% right. Also, this was fun.</em></p><p>The package isn’t totally complete yet. The most notable omission is (ironically) unit tests. I’m busy preparing for my PhD viva in a couple weeks, so hopefully I’ll get around to those after.</p><p>If you have suggestions for features, please let me know on <a href="https://github.com/aido179/apb-mocha-reporter">github</a>!</p><p>I’m <a href="https://twitter.com/aidanbreen">Aidan Breen</a>, and I run a <a href="http://apbsoftware.ie/">software consultancy</a> in Dublin, Ireland. If you enjoyed this post, consider following me on <a href="https://twitter.com/aidanbreen">twitter</a>, or signup to my <a href="https://apbsoftwareandhardware.us3.list-manage.com/subscribe?u=bd4ace12c9503b0fb9dde0282&amp;id=6081e1a8d6">personal mailing list</a> for less than monthly updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45b098d95ef6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Docker? Don’t forget to use build caching!]]></title>
            <link>https://medium.com/@aidobreen/using-docker-dont-forget-to-use-build-caching-6e2b4f43771e?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e2b4f43771e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 12:24:52 GMT</pubDate>
            <atom:updated>2018-11-06T12:24:52.690Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a quick and easy tip that will speed up your docker builds for Python, Nodejs or any project that requires installing dependencies…</p><blockquote>If you are installing dependencies, <strong>copy only your dependency list before installing</strong> (package.json in Node or requirements.txt in python with pip), <strong>then move your application code.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*ekwSFfthN3j2tT2GzjbRLg.jpeg" /><figcaption>The struggle for relevant images continues…</figcaption></figure><h3>Python example:</h3><p>If your Dockerfile looks something like this:</p><pre>FROM python:3.6-alpine<br>COPY . /app<br>RUN pip install -r /requirements.txt<br>CMD [ &quot;python&quot;, &quot;/app/yourscript.py&quot; ]</pre><p>Change it to:</p><pre>FROM python:3.6-alpine<br>COPY requirements.txt /<br>RUN pip install -r /requirements.txt<br>COPY . /app<br>CMD [ &quot;python&quot;, &quot;/app/yourscript.py&quot; ]</pre><h3>Node example:</h3><p>If your Dockerfile looks something like this:</p><pre>FROM node:8<br>COPY . /app<br>RUN npm install --production<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;app/index.js&quot;]</pre><p>Change it to:</p><pre>FROM node:8<br>COPY package.json /app/package.json<br>RUN cd /app; npm install --production<br>COPY . /app<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;app/index.js&quot;]</pre><h3>Note for both Node and Python</h3><p>In both Node and Python, the dependencies are stored in a file by name and version so that application code can be deployed without dependencies, which can be pulled in later. <strong>These dependency files only change when a new dependency is installed (or an old one is updated).</strong></p><p>Docker is smart enough to know that if a file hasn’t changed, the build steps after it don’t need to be run again. So npm install and pip install (the slowest steps of the build) are skipped!</p><h3>Conclusion</h3><p>I’ve modified the example dockerfiles for brevity — removed comments and extra steps that I use in reality.</p><p>Got an example in another programming language? Let me know.</p><p>If you enjoyed this post, consider following me on <a href="https://twitter.com/aidanbreen">twitter</a>, or signup to my <a href="http://Ok, screw it. Let&#39;s give this a go and see what happens:  http://eepurl.com/dMEsHg">personal mailing list</a> for less than monthly updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e2b4f43771e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS: Promises, async/await, and functional programming.]]></title>
            <link>https://medium.com/@aidobreen/js-promises-async-await-and-functional-programming-f2e5fa66b4ef?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2e5fa66b4ef</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Tue, 02 Oct 2018 15:58:13 GMT</pubDate>
            <atom:updated>2018-11-06T12:29:55.327Z</atom:updated>
            <content:encoded><![CDATA[<p>Unlike a lot of the internet, I happen to enjoy writing Javascript. I’m also a fan of functional programming; from a practical point of view, and from an aesthetic point of view. In the art of code, functional is beautiful.</p><p>Unfortunately, like most JS developers, my love of functional code is at odds with the asynchronous nature of the language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYLUnXgd_Cpzzka3oxOirQ.jpeg" /><figcaption>Honestly, how does one find a suitable picture that represents functional programming? This is pretty though.</figcaption></figure><h3>Here’s the challenge:</h3><ol><li>The web is inherently <strong>asynchronous</strong>. Waiting for network requests, user input or animations — they all need to happen without holding up the rest of our code. <br><em>(Aside: Async is not unique to the web of course. And as any programmer who has dealt with multithreaded systems with tell you: It’s never simple.)</em></li><li>Functional programming doesn’t naturally map to asynchronous tasks. <strong>Why?</strong> A pure function should have two attributes: <br>A) It should be <strong>deterministic</strong>: For a specific input, it should always produce the same output.<br>B) It should not have<strong> side effects:</strong> that is, a function should not affect anything outside itself. Further, it should not rely on anything in the global state.</li></ol><p>Here are some examples:</p><pre><strong>// Functional - Deterministic and side-effect free.</strong><br>function add(x, y){<br>    return x + y;<br>}</pre><pre><strong>// Not functional - Not deterministic (still side effect free)</strong><br>function addRand(x){<br>    return x + Math.random();<br>}</pre><pre><strong>// Not functional - Deterministic, but has side-effects</strong><br>var k = 6;<br>function addToGlobal(x){<br>    k += x;<br>    return k;<br>}</pre><pre><strong>// Not functional - Not deterministic and has side-effects<br></strong>var k = 6;<br>function addRandToGlobal(x){<br>    k += (x*Math.random());<br>    return k;<br>}</pre><h4>How does this conflict with asynchronous programming?</h4><p>Let’s assume you want to calculate something based on an asynchronous request: the value of a user’s ETH wallet (Ethereum crypto currency tokens) in USD. You would take the total number of ETH, and multiply it by the most recent exchange rate — which you get from an API somewhere.</p><pre>var ethWallet = 2.3;<br>function getETHinUSD(){<br>    let rate = api.ethPrice(&#39;USD&#39;);<br>    return ethWallet*rate;<br>}</pre><p>There are a few issues here.</p><p><strong>First</strong> and foremost, event though there isn’t a side-effect, ethWallet is still a global variable, which we want to avoid. Instead, let’s pass it to the function as a parameter.</p><pre>function getETHinUSD(ethWallet){<br>    let rate = api.ethPrice(&#39;USD&#39;);<br>    return ethWallet*rate;<br>}</pre><p><strong>Second,</strong> assuming the api.ethPrice() function is asynchronous, this code will probably just throw an error. This is because rate will not have a value until api.ethPrice() finishes, but there is nothing telling our code to wait for api.ethPrice() , so the function will return the result of ethWallet*rate , before rate has a value.</p><p>There are two ways to fix this. <strong>Promises</strong>, or <strong>async/await</strong>.</p><h3><strong>Promises</strong></h3><p>I’m not going to go into detail on promises here, there are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">much better resources out there</a>. But to remind you:</p><blockquote>A promise is simply an object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.</blockquote><p>In a nutshell, Promises either complete (resolve) or fail (reject). We can do something when a promise completes by using the then() function, and do something when it fails by using the catch() function.</p><p>Let’s assume api.ethPrice() returns a Promise. In the last example, rate would become a Promise object, which would have a then() function. <br>We <em>could </em>call rate.then( fn(result) ) with a callback function called fn which will receive result when the promise completes. <br><strong>OR</strong><br>We could implicitly treat api.ethPrice() as a promise, and use then directly:</p><pre>function getETHinUSD(ethWallet){<br>    return api.ethPrice(&#39;USD&#39;).then(function(rate){<br>        return ethWallet*rate;<br>    })<br>}</pre><p>Promises also do this funky thing called chaining. The then function also returns a promise, which means we could do something else asynchronously inside that inner function and have a then after that too. This chain also allows us to handle errors nicely. We can just put one catch at the end, and it will handle any asynchronous failures:</p><pre>function getETHinUSD(ethWallet){<br>    return api.ethPrice(&#39;USD&#39;)<br>    .then(function(rate){<br>        return ethWallet*rate;<br>    })<br>    .catch(function(error){<br>        console.log(&quot;Something went wrong:&quot;, error);<br>        return false;<br>    })<br>}</pre><p>Lovely, but there’s still one problem: <strong>It’s not even close to functional.</strong></p><p><strong>Deterministic? </strong>getETHinUSD will return a different value at different times — even with the same input. That’s OK if we expect the USD exchange rate to change over time, but that’s not all. If the api request fails, we don’t get the same value, but we don’t even get the same data type!</p><p><strong>Side-effects?</strong> The function getETHinUSD itself does not affect our global state, but what about the inner function passed to then ? It relies on the value of ethWallet, which cannot be passed directly. <br>And what about the api call itself? How do we know this function isn’t affecting the global state of our app through some other method? Maybe by requesting the ETH price, it updates a request counter for our user state, limiting the number of requests we can make, preventing api access after X requests, or just invalidating our credentials and effectively logging us out of the whole api?</p><h3>Async/await</h3><p>There is another approach that involves creating an <strong>asynchronous function. </strong>Again, the details are beyond the scope of this article, but are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">described excellently elsewhere.</a> Again, to jog your memory:</p><blockquote>An asynchronous function is a function which operates asynchronously using async/await syntax… <br>… using async functions is much more like using standard synchronous functions.</blockquote><p>Kurzgesagt, we can user the async keyword to identify a function that will need to wait for something in it’s body to complete. Within the async function, we use the await keyword to identify what we want to wait for.</p><p>Once again, starting with:</p><pre>function getETHinUSD(ethWallet){<br>    let rate = api.ethPrice(&#39;USD&#39;);<br>    return ethWallet*rate;<br>}</pre><p>We identify getETHinUSD as an asynchronous function, and we wait for the result of api.ethPrice() :</p><pre>async function getETHinUSD(ethWallet){<br>    let rate = await api.ethPrice(&#39;USD&#39;);<br>    return ethWallet*rate;<br>}</pre><p>This already looks really nice — right? <br>What happens if the api fails? Well, we have to use a good old try/catch.</p><pre>async function getETHinUSD(ethWallet){<br>    try{<br>        let rate = await api.ethPrice(&#39;USD&#39;);<br>        return ethWallet*rate;<br>    } catch (error){<br>        console.log(&quot;Something went wrong:&quot;, error)<br>        return false<br>    }<br>}</pre><p><strong>Is this deterministic?</strong> Not if the we assume the api returns a different value over time and never fails.</p><p><strong>Are there side effects?</strong> Possibly, but at least visually, we don’t see the same inner function accessing the parent function scope. However, because async/await still uses promises under the hood, it’s technically still happening — it just doesn’t affect us.</p><p>The api may still have side effects, but we don’t have a choice about that.</p><h3>Side by side comparison</h3><p>Using Promises:</p><pre>function getETHinUSD(ethWallet){<br>    return api.ethPrice(&#39;USD&#39;)<br>    .then(function(rate){<br>        return ethWallet*rate;<br>    })<br>    .catch(function(error){<br>        console.log(&quot;Something went wrong:&quot;, error);<br>        return false;<br>    })<br>}</pre><p>Using async/await:</p><pre>async function getETHinUSD(ethWallet){<br>    try{<br>        let rate = await api.ethPrice(&#39;USD&#39;);<br>        return ethWallet*rate;<br>    } catch (error){<br>        console.log(&quot;Something went wrong:&quot;, error)<br>        return false<br>    }<br>}</pre><h4>Some observations</h4><ol><li>The Promise version is longer in terms of lines of code by a whopping single line. I’ve seen many blog posts calling this a win for async/await, but to be honest, that is not going to make much difference in a codebase of 10,000+ lines.</li><li>The async/await version is still using promises, they are just hidden in the syntax.</li><li>The async/await version looks more like our synchronous version, without handling the asynchronous api call. Is this a win? Many blogs seem to think so. I personally don’t. <br>At a glance, it is easy to tell that there is something odd happening with the Promise version. The difference is subtle, but straight away, we know that something asynchronous is happening — By structure rather than syntax, we know rate will not have an immediate value. <br>The argument could, of course, be made that the literal inclusion of the word async makes it obvious enough.</li><li>In a longer chain of asynchronous operations, what are these two approaches going to look like? <br>In my current day-job codebase, we have a few key controller functions with many asynchronous steps. <br><strong>Imagine creating a new widget:</strong><br>a) You need to validate the user (async)<br>b) <em>then</em> You need to add the new widget to the database.<br>c) <em>then</em> You need to update 3 gadgets that reference the new widget.<br>d) <em>then</em> You need to notify 2 users that are using each gadget (6 in total) that a widget has been created.<br>e) <em>then</em> You need to log that this has all happened successfully. <br><strong>If any one of those steps fails, we want to log a different message and role back as much as possible.<br></strong>Using async/await, we would probably put each await call in a single try block and handle the catch at the end. But what if we wanted separate catch blocks for some awaits and not others? Imagine what that would look like! <br>Now consider each step happens in a neat then() function, and separate failures can be handled by individual catch()’s, all chained together.</li></ol><h4>What about being Functional?</h4><p>The fact is that if you have a non-deterministic api call, you simply cannot write a pure function. However, in JavaScript, functional programming is always going to be a <em>best-effort</em> situation. The language is not designed to be truly functional.</p><p>No matter what approach you use, you can separate your function code from your non-functional code. <strong>Be functional where you can to maintain an understandable, maintainable codebase.</strong></p><p>When you think <em>functional</em> javascript, you probably also think <em>function chaining. </em>Promises allow us to chain asynchronous sections of code in a functional way. We can treat each then <em>like</em> a function returned by the previous then (even if it’s actually a method of a Promise object…).</p><pre>&lt;Array&gt;.map().filter().sort()</pre><pre>&lt;Promise&gt;.then().then().catch().finally()</pre><p>See the similarity? Using await encourages you not to chain asynchronous requests, rather to use intermediate values.</p><pre>let intermediateValue1 = await asynchronousFunction1() ;<br>let intermediateValue2 = await asynchronousFunction2() ;<br>let intermediateValue3 = await asynchronousFunction3() ;</pre><p>It’s procedural. <br>(Not a bad thing! But the topic of this post is being functional…)</p><p>This is useful in certain situations, such as using intermediateValue1 as an argument of asynchronousFunction3(). You end up storing the result in an intermediate variable outside of the promise chain anyway. This is a huge benefit of async/await — but it’s less functional in my opinion.</p><p>Of course, because await returns an implicit promise anyway, you could turn it into a promise chain:</p><pre>await asynchronousFunction().then(...);</pre><p>Best of both worlds, or unholy hackery? I’ll let you decide for yourself.</p><h3>Conclusion</h3><p>This might look like I have a preference for Promises, but to be honest, it all boils down to one thing: <strong>Use the right tool for the job!</strong></p><ul><li>If your code base already uses one approach exclusively, continue using that. It’ll save somebody a good deal of confusion.</li><li>If one approach is clearly easier to understand in a given context, use the more obvious solution!</li><li>If in doubt, ask a colleague. If you don’t have a colleague (lucky you) try both and see which feels better.</li></ul><p>Thanks for reading!</p><p>I’m <a href="https://twitter.com/aidanbreen">Aidan Breen</a>, and I run a <a href="http://apbsoftware.ie/">software consultancy</a> in Dublin, Ireland.</p><p>If you enjoyed this post, consider signing upto my <a href="http://Ok, screw it. Let&#39;s give this a go and see what happens:  http://eepurl.com/dMEsHg">personal mailing list</a> for less than monthly updates.</p><p>Many thanks to <a href="https://twitter.com/mikevanrossum">Mike</a> <a href="https://mikevanrossum.nl/">van</a> <a href="https://github.com/askmike">Rossum</a> for proof reading this post and providing really valuable and insightful feedback.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2e5fa66b4ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing the launch of Posture!]]></title>
            <link>https://medium.com/@aidobreen/announcing-the-launch-of-posture-584adc5d5a4a?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/584adc5d5a4a</guid>
            <category><![CDATA[startup-marketing]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[product-design]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[product]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Tue, 24 Apr 2018 14:09:09 GMT</pubDate>
            <atom:updated>2018-04-24T14:09:09.381Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDRW7YTM6gwW1kFpfZJWEQ.jpeg" /><figcaption>The first complete unit on display at the NUIG Blackstone Launchpad, Galway</figcaption></figure><p>This will be a quick post, but I have to share! After months and months of work, the first units of the Posture Laptop Stand are finally ready to be shipped!</p><p>It’s been a super long road, and I’m eternally grateful to everybody who has helped along the way, including all of the wonderful early-bird customers!</p><p>Posture is on sale over at <a href="https://tryposture.com/">tryposture.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=584adc5d5a4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hidden text fingerprints and how to avoid them.]]></title>
            <link>https://medium.com/@aidobreen/hidden-text-fingerprints-and-how-to-avoid-them-d0103edd2ce4?source=rss-ecef87284345------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0103edd2ce4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[chrome]]></category>
            <dc:creator><![CDATA[Aidan Breen]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 15:05:13 GMT</pubDate>
            <atom:updated>2018-11-06T12:31:57.741Z</atom:updated>
            <content:encoded><![CDATA[<p>This post is inspired by <a href="https://medium.com/@umpox/be-careful-what-you-copy-invisibly-inserting-usernames-into-text-with-zero-width-characters-18b4e6f17b66">a blog post</a>, a <a href="https://news.ycombinator.com/item?id=16749422">discussion on HN</a>, and a <a href="https://news.ycombinator.com/item?id=16754987">chrome extension</a>. The final result is <a href="https://chrome.google.com/webstore/detail/zwblocker/halgnbpginjdhipahdncmimakhmdohob">zwBlocker: An extension that helps spot zero-width characters.</a></p><p><strong>It all revolves around a basic idea</strong>: Your name (or email, username etc.) can be invisibly hidden in a piece of text that you copy and share somewhere else, identifying you as the person who shared it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTSX1l1vz7GD86LzttJW3A.png" /><figcaption>Yes, it’s a cheesy lede image — but to be fair, at least it’s not HTML.</figcaption></figure><h4><strong>How?</strong></h4><p><a href="https://medium.com/@umpox/be-careful-what-you-copy-invisibly-inserting-usernames-into-text-with-zero-width-characters-18b4e6f17b66">Tom’s post</a> describes the concept in great detail, but the basic idea makes use of <em>unicode characters with zero-width</em>.</p><p>That is, when you insert a zero-width character into a piece of text, it will not be visible and will not (or may not) affect the rest of the text. However, these zero-width characters can be read by a machine and by using a series of these zero-width characters, we can encode invisible information into any piece of text — when an email is sent for example — and read it back later, when the text shows up on social media.</p><h4><strong>What can I do to avoid this?</strong></h4><p><strong>Most obvious approach:</strong> Simply take a screenshot of the text and share that. This way, zero-width characters can not be read, and names can be blurred out. Sadly, this isn’t the only way your name could be encoded. <br><strong>Why that wont work:</strong> As HN user <a href="https://news.ycombinator.com/item?id=16756456">boramalper</a> suggests, other aspects such as ligatures, margins, fonts, kerning or even synonym replacement may be used to encode your identity, even from a screen shot.</p><p><strong>A better approach:</strong> Don’t copy the hidden characters in the first place!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHW_cvZjkfUDgveLoloF9g.gif" /><figcaption>chpmrc’s chrome extension at work.</figcaption></figure><p>About 12 hours after the first HN discussion, a <a href="https://news.ycombinator.com/item?id=16754987">chrome extension was posted </a>by user chpmrc to help do just that! It works rather simply — if you suspect there are hidden characters in the text, you open up the chrome extension, click the button and<em> boom!</em> All zero-width characters are replaced by emojis.</p><p><strong>This is great, except for one thing: There is no way I would remember to do that! </strong>And <a href="https://news.ycombinator.com/item?id=16755668">I’m not the only one</a>.</p><h3>A better solution</h3><p>Many suggestions were made, including:</p><blockquote>strip the non-printing characters and display a number of characters stripped, similar to how ad blockers display the number of ads blocked.-<a href="https://news.ycombinator.com/item?id=16755668">kerkeslager</a></blockquote><blockquote>scan your clipboard for zero-width characters, silently strip them, and then re-populate the clipboard. -<a href="https://news.ycombinator.com/item?id=16755671">Someone1234</a></blockquote><p>and wryly:</p><blockquote>read the web exclusively in ASCII with UTF-8 characters inserted using their codepoint. -<a href="https://news.ycombinator.com/item?id=16761775">flashman</a></blockquote><p>Personally, I think automatically stripping characters might lead to some issues, particularly with emoji support where zero-width characters can be used to change how certain emojis are displayed (changing skin tone etc.)</p><p>I also feel manipulating people’s clipboards would be a risky manoeuvre — particularly if people <em>want</em> to copy zero-width characters for legitimate purposes. Not to mind, it would be difficult to implement.</p><p><strong>In my opinion, the ideal solution would be an extension that:</strong></p><p>1. Quietly warns you of hidden characters, similar to how ad-blockers show how many ads have been blocked, but don’t strip them.</p><p>2. Loudly warns you when you have selected text with hidden characters. This way, even if you forgot you installed the extension, you are still protected.</p><h3>Building the ideal solution</h3><blockquote>“Ok, what do we do when the existing solutions don’t suit our needs?”<br>“We look harder, make do with what we have, or give up!”<br>“No! We waste a Sunday afternoon (and most of Monday) building a custom solution!”</blockquote><p>Functionally, we need the extension to:</p><ul><li>Read the content of pages we visit.</li><li>Edit the content of pages we visit.</li><li>Show a popup UI when necessary.</li></ul><p>Thankfully, an extension I have previously built does all of that: <a href="https://chrome.google.com/webstore/detail/squish/bibdnpefpfgdgbficnmcffagemhbpldf">Squish</a> makes tall tweets shorter. You can read about how I built Squish in a <a href="https://medium.com/@aidobreen/fixing-twitter-with-a-chrome-extension-1f53320f5a01">previous blog post</a>, and see the code behind it on <a href="https://github.com/aido179/squish">github</a>.</p><h4>How to…</h4><blockquote>This will be super brief — leave a comment if you would like to read an in-depth post on how it’s made.</blockquote><p>Starting with the Squish code, I am going to delete all the promo images then update the readme.md and the manifest to call our new project: <strong>zwBlocker: </strong><em>Find and notify the user of zero-width unicode characters.</em></p><h4>manifest.json</h4><p>Squish only worked on “twitter.com”, so we want to change the manifest to let our new extension access every page we visit. Under content-scripts, change “matches” to:</p><pre>&quot;matches&quot;: [&quot;&lt;all_urls&gt;&quot;],</pre><p>To find zero-width characters on the page, we’ll use a content-script which runs after the page loads: ”run_at”: “document_end”.</p><h4>Walking the DOM to find those pesky buggers</h4><p>We’re going to use a treeWalker to search the DOM for zwc’s. It’s created with the factory method <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker">document.createTreeWalker</a> which accepts a filter function we can write to identify nodes we are interested in. Our filter function looks like this:</p><pre><strong>contentScript.js</strong></pre><pre>...<br>function(node) {<br>  if(testForZeroWidthCharacters(node.nodeValue)){<br>    totalCount++;<br>    return NodeFilter.FILTER_ACCEPT;<br>  }<br>  else{<br>    //FILTER_SKIP should keep the children of this node in consideration.<br>    return NodeFilter.FILTER_SKIP;<br>  }<br>}<br>...</pre><p><a href="https://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeFilter">NodeFilter.FILTER_ACCEPT and </a><a href="https://www.w3.org/TR/DOM-Level-2-Traversal-Range/traversal.html#Traversal-NodeFilter">FILTER_SKIP</a> are constants that tell the treeWalker to include the current node, or skip it. There is a third possibility here of FILTER_REJECT which would ignore the children of the current node. This would make searching the tree much quicker if we could be sure no text children existed, but we can’t, so we wont :).</p><p>totalCount is a global var I use to keep track of how many zwc’s we’ve found.</p><p>testForZeroWidthCharacters is my own function, heavily based off <a href="https://github.com/chpmrc/zero-width-chrome-extension">chpmrc’s code</a> and looks like:</p><pre><strong>contentScript.js</strong></pre><pre>...<br>var zwMatches = /[\u200B-\u200D\uFEFF]/g;<br>function testForZeroWidthCharacters(text){<br>  return text.match(zwMatches);<br>}<br>...</pre><p>The zwMatches regex is outside the function because I’ve also written functions to remove and replace zwc’s using the same regex. The regex ends with g meaning it is a global regex, and will match ALL occurrences — rather than just the first one. Pretty important when removing and replacing zwc’s!</p><h4>Capturing selected text</h4><p>I didn’t know this, but it turns out you can use document.onselectionchange to track every time the user highlights text on the page. selection.toString() got me the text, including any possible zwc’s — which I could then pass to my regex function, and send on to the background script to notify the user. Simple!</p><pre>//catch selected text and send message to background page<br>document.onselectionchange = function() {<br>  var selection = document.getSelection();<br>  if(testForZeroWidthCharacters(selection.toString())){<br>    chrome.storage.sync.set({<br>      selectedText: selection.toString(),<br>      selectedTextClean:removeZeroWidthCharacters(selection.toString()),<br>      selectedTextEmoji:replaceZeroWidthCharacters(selection.toString()),<br>    },function(){});<br>    /* show message*/<br>    chrome.runtime.sendMessage({message: &quot;warnUserOfZeroWidthChars&quot;, value:selection.toString()}, function(response) {<br>    });<br>  }<br>};</pre><h4>And the rest…</h4><p>The rest of the code is very straightforward:</p><p>Passing messages between the content-script and the background page using <a href="https://developer.chrome.com/extensions/runtime">chrome.runtime.sendMessage</a> and onMessage.</p><p>Showing notifications to the user using <a href="https://developer.chrome.com/extensions/notifications">chrome.notifications.create</a> and chrome.notifications.onButtonClicked.</p><p>Create a new tab with <a href="https://developer.chrome.com/extensions/tabs">chrome.tabs.create</a>. Pass the sanitised text with <a href="https://developer.chrome.com/extensions/storage">chrome.storage.sync</a>.</p><p>I’ll spare you the detail here.</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_cPkVHn4plWTQBzBLisBmQ.gif" /><figcaption>zwBlocker in action!</figcaption></figure><p>Say hello to <a href="https://chrome.google.com/webstore/detail/zwblocker/halgnbpginjdhipahdncmimakhmdohob">zwBlocker</a>: A Chrome extension that:</p><ul><li>Subtly shows the number of zero-width characters on the page.</li><li>Detects zero-width characters in selected text, and notifies the user.</li><li>Filters out zero-width characters when requested.</li></ul><p>I’m pretty happy with the result — not bad for a weekend of work! Of course, improvements can be made. Feel free to comment here, on <a href="https://twitter.com/aidanbreen">twitter</a> or create an issue or pull request on <a href="https://github.com/aido179/zwBlocker">github</a>.</p><p>I also want to say thanks to the creators who inspired this post. I love seeing active discussion and work on this kind of stuff.</p><p>I’m <a href="https://twitter.com/aidanbreen">Aidan Breen</a>, and I run a <a href="http://apbsoftware.ie/">software consultancy</a> in Dublin, Ireland. If you enjoyed this post, consider following me on <a href="https://twitter.com/aidanbreen">twitter</a>, or signup to my <a href="http://Ok, screw it. Let&#39;s give this a go and see what happens:  http://eepurl.com/dMEsHg">personal mailing list</a> for less than monthly updates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0103edd2ce4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>