<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Shovon Hasan - Blog]]></title><description><![CDATA[#100daysofcode except... forever.]]></description><link>https://blog.shovonhasan.com/</link><image><url>https://blog.shovonhasan.com/favicon.png</url><title>Shovon Hasan - Blog</title><link>https://blog.shovonhasan.com/</link></image><generator>Ghost 2.25</generator><lastBuildDate>Sun, 12 Apr 2026 11:20:11 GMT</lastBuildDate><atom:link href="https://blog.shovonhasan.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Easily fixing security vulnerabilities in transitive dependencies with Yarn.]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>It's 4:30 on a Friday and GitHub hits you with one of these:</p>
<p><img src="https://blog.shovonhasan.com/content/images/2019/07/github-security-alert.PNG" alt="github-security-alert"></p>
<p>How do you make this go away and still get home on time? If GitHub's automated security fixes feels like admitting defeat or errors out on you, Yarn can make it easy.</p>
<p>If Github's vulnerability report</p>]]></description><link>https://blog.shovonhasan.com/fixing-a-security-vulnerability-in-a-transitive-dependency/</link><guid isPermaLink="false">5d3953fba332c51331d0e3af</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Thu, 25 Jul 2019 04:39:10 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/steve-johnson-F3ig12CrnGo-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://blog.shovonhasan.com/content/images/2019/07/steve-johnson-F3ig12CrnGo-unsplash.jpg" alt="Easily fixing security vulnerabilities in transitive dependencies with Yarn."><p>It's 4:30 on a Friday and GitHub hits you with one of these:</p>
<p><img src="https://blog.shovonhasan.com/content/images/2019/07/github-security-alert.PNG" alt="Easily fixing security vulnerabilities in transitive dependencies with Yarn."></p>
<p>How do you make this go away and still get home on time? If GitHub's automated security fixes feels like admitting defeat or errors out on you, Yarn can make it easy.</p>
<p>If Github's vulnerability report looks like this:</p>
<p><img src="https://blog.shovonhasan.com/content/images/2019/07/vulnerability_report.PNG" alt="Easily fixing security vulnerabilities in transitive dependencies with Yarn."></p>
<p>And you don't depend on <code>lodash</code> directly (meaning it's a transitive dependency), an easy solution is to add a &quot;resolutions&quot; field to your <code>package.json</code> with the patched version within its semver range. So in this case our <code>package.json</code> would include these lines:</p>
<pre><code class="language-json">  &quot;resolutions&quot;: {
    &quot;lodash&quot;: &quot;^4.17.13&quot;
  },
</code></pre>
<p>Now if you run <code>yarn</code>, it'll update your <code>yarn.lock</code> file to force every transitive dependency to use the patched version instead. Afterwards, if you push up your new <code>yarn.lock</code> to GitHub, the warning will disappear. 🎉</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Writing Type-safe Defaults with TypeScript's Pick Type]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>A common pattern I use when writing TypeScript applications is creating default objects and overwriting some or all of those defaults with data provided by the user. But there's a common mistake when implementing this pattern that can be fixed with a little knowledge of TypeScript's built in utilities.</p>
<h1 id="implementationofthedefaultpattern">Implementation</h1>]]></description><link>https://blog.shovonhasan.com/writing-type-safe-defaults-with-typescript/</link><guid isPermaLink="false">5d3953fba332c51331d0e3a9</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Tue, 15 May 2018 00:30:07 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/john-fowler-9270-pFGVTU-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://blog.shovonhasan.com/content/images/2019/07/john-fowler-9270-pFGVTU-unsplash.jpg" alt="Writing Type-safe Defaults with TypeScript's Pick Type"><p>A common pattern I use when writing TypeScript applications is creating default objects and overwriting some or all of those defaults with data provided by the user. But there's a common mistake when implementing this pattern that can be fixed with a little knowledge of TypeScript's built in utilities.</p>
<h1 id="implementationofthedefaultpattern">Implementation of the default pattern</h1>
<p>Here's some code you might see in an app where <code>ReadingListEntry</code> objects are generated from a mix of defaults and user input, for example.</p>
<script src="https://gist.github.com/Anveio/4a7ec46148ae4e2d1e1da4b5e664781d.js"></script>
<p>I like this pattern a lot, and it's especially good as the complexity of data in an application scales up. When objects have many fields or when users have multiple ways of creating data entries, centralizing defaults like this reduces a lot of boilerplate code (<a href="https://github.com/tc39/proposal-object-rest-spread">especially when combined with the Stage 4 object spread operator</a>). And when things go wrong, it makes finding the culprit a lot easier.</p>
<p>But there's a problem with the way we're setting our defaults. To satisfy the TypeScript compiler, the default reading list entry's <code>createdOn</code> and <code>id</code> properties are set to unusable values. It may not seem like a big deal because we can see that those fields are <em>always</em> being overwritten with data from the user. But say we call <code>generateReadingListEntry</code> and <em>forget</em> to overwrite the default <code>id</code> value? <strong>The compiler wouldn't tell us about our mistake and our application would fail silently.</strong></p>
<p><img src="https://blog.shovonhasan.com/content/images/2018/05/no-compiler-error.PNG" alt="Writing Type-safe Defaults with TypeScript's Pick Type"></p>
<p>A mistake like this can and should be caught at compile time. Otherwise, this could end in a poor user experience at best or be catastrophic to the integrity of the user's data at worst.</p>
<h1 id="picktotherescue">'Pick' to the rescue</h1>
<p>The best way to architect this pattern is to declare which properties of the <code>ReadingListEntry</code> object are safe to leave as default values and which ones we should always make sure to set manually when creating a <code>ReadingListEntry</code> object.</p>
<p>Fortunately, TypeScript has built in tools to make this possible. We can remove the <code>id</code> and <code>createdOn</code> properties of <code>defaultReadingList</code> and instead of annotating it as a full <code>ReadingListEntry</code> we can use TypeScript's <code>Pick</code> type to declare which properties of <code>ReadingListEntry</code> it has.</p>
<script src="https://gist.github.com/Anveio/e7a3f61b96afdbc649fea81fc31eb90c.js"></script>
<p>Now, if we use <code>defaultReadingList</code> to create <code>ReadingListEntry</code> objects, the TypeScript compiler will throw an error when we forget to manually set the missing properties.</p>
<p><img src="https://blog.shovonhasan.com/content/images/2018/05/compiler-error.PNG" alt="Writing Type-safe Defaults with TypeScript's Pick Type"></p>
<p>We can even add a bit of expressiveness by giving the keys we're <code>Pick</code>ing a name:</p>
<script src="https://gist.github.com/Anveio/2214de2c2b97820da346cb83dc005113.js"></script>
<p>In my experience with TypeScript's <a href="http://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types">mapped types</a> Pick has proven to be the most useful. It allows for creating type-safe partial slices of objects without needing to rely on TypeScript's inferencing or a complex naming strategy.</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Using Absolute Imports with Jest in Create React App]]></title><description><![CDATA[Jest's modulePaths option makes it possible.]]></description><link>https://blog.shovonhasan.com/using-absolute-imports-with-jest-in-create-react-app/</link><guid isPermaLink="false">5d3953fba332c51331d0e3a7</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Sat, 07 Apr 2018 17:26:14 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/dominik-lange-ZUvF7qEIcVI-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><h2 id="theproblem">The problem</h2>
<img src="https://blog.shovonhasan.com/content/images/2019/07/dominik-lange-ZUvF7qEIcVI-unsplash.jpg" alt="Using Absolute Imports with Jest in Create React App"><p>You've written your <code>create-react-app</code> application using absolute imports resolved from e.g. a folder named <code>src</code> but when you run your tests you get a message like this:</p>
<p><img src="https://blog.shovonhasan.com/content/images/2018/04/absolute_import_error.PNG" alt="Using Absolute Imports with Jest in Create React App"></p>
<h2 id="theexplanation">The explanation</h2>
<p>You may have configured Webpack or the TypeScript compiler to resolve absolute imports from the <code>src</code> folder but Jest doesn't yet know about that configuration.</p>
<p>You can tell Jest about your absolute import resolution strategy by passing another option to the default <code>create-react-app</code> <code>test</code> script. Specifically, it's <a href="https://facebook.github.io/jest/docs/en/configuration.html#modulepaths-array-string">Jest's <code>modulePaths</code> option</a> that makes this possible.</p>
<h2 id="thesolution">The solution</h2>
<p>To use Jest's <code>modulePaths</code> option, add <code>--modulePaths=src</code> to the end of the <code>test</code> script in your <code>package.json</code>. If your imports resolve from the <code>src</code> folder, for example, you would change the script to this:</p>
<p><img src="https://blog.shovonhasan.com/content/images/2018/04/changed-script.PNG" alt="Using Absolute Imports with Jest in Create React App"></p>
<p>Although the image above shows the option being passed to <code>react-scripts-ts</code> it should work for regular <code>react-scripts</code> as well. Now if you run your tests Jest is able to resolve your absolute imports.</p>
<p><img src="https://blog.shovonhasan.com/content/images/2018/04/fixed-version.PNG" alt="Using Absolute Imports with Jest in Create React App"></p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Using Promises with FileReader]]></title><description><![CDATA[Using `await` to handle FileReader's asynchronicity can be a lot simpler than dealing with events.]]></description><link>https://blog.shovonhasan.com/using-promises-with-filereader/</link><guid isPermaLink="false">5d3953fba332c51331d0e3a6</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Mon, 27 Nov 2017 01:32:00 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/hope-house-press-leather-diary-studio-IOzk8YKDhYg-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><h2 id="understandingfilereader">Understanding FileReader</h2>
<img src="https://blog.shovonhasan.com/content/images/2019/07/hope-house-press-leather-diary-studio-IOzk8YKDhYg-unsplash.jpg" alt="Using Promises with FileReader"><p>The FileReader API is event driven. You define custom behavior in <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader#Event_handlers">its event handlers</a> when it either succeeds or fails to read a file and then pass a File object to <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader#Methods">one of the methods, such as <code>readAsText</code></a> The result of the method, if successful, can finally be retrieved in the <code>.result</code> property.</p>
<p>The FileReader methods work asynchronously but don't return a Promise. And attempting to retrieve the result immediately after calling a method will not work, as the <code>.onload</code> event handler fires only after the FileReader has successfully finished reading the file and updates the FileReader's <code>.result</code> property. This can make FileReader a bit of a pain to work with when integrating it with an application.</p>
<h2 id="wrappingitwithapromise">Wrapping it With a Promise</h2>
<p>A solution to make FileReader more pleasant to work with is to wrap its result in a Promise. Here's an example:</p>
<script src="https://gist.github.com/Anveio/05d65f759e3ab0ecd97542b04192deb4.js"></script>
<p>This function returns a Promise of a string that will resolve or reject only after the firing of the <code>.onload</code> and <code>.onerror</code> event handlers, respectively. If the Promise is rejected the FileReader will abort and, in this case, return a custom DOMException but you can <code>reject</code> with whatever you like. One good alternative is the FileReader's <code>.error</code> property, which will also be a DOMException.</p>
<h2 id="asimplifiedapiwithasyncawait">A Simplified API with Async/Await</h2>
<p>Wrapping the result of a FileReader in a Promise allows us to <code>await</code> the result of our <code>readUploadedFileAsText</code> function and expect a string. Here's an example <code>onchange</code> handler we could pass to a <code>&lt;input type=&quot;file /&gt;</code> element (<a href="https://codepen.io/Anveio/pen/XzYBzX">Full example on CodePen</a>)</p>
<script src="https://gist.github.com/Anveio/546eb2206e55c52bb3681ec6979849c7.js"></script>
<h2 id="reactexamples">React Examples</h2>
<p>The CodePen link above shows the above code doing manual DOM manipulation. <a href="https://codesandbox.io/s/lrjxj8w867">Here's an example of using the same readUploadedFileAsText function with async/await in a React application</a>.</p>
<iframe src="https://codesandbox.io/embed/lrjxj8w867" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe>
<p><a href="https://github.com/Anveio/mturk-engine/blob/b1077f6c0fef6192c4b81803c12f80ff4152fd97/src/components/BackupUserSettings/ImportUserSettings.tsx">For an example in a TypeScript and React application, look here</a>. Though this particular code example is part of an application using Redux so there's a fair bit of indirection.</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Pattern for Rendering Lists of Connected Components with React-Redux]]></title><description><![CDATA[The key is in the second argument of your `mapStateToProps` function.]]></description><link>https://blog.shovonhasan.com/pattern-for-rendering-lists-of-connected-components-with-react-redux/</link><guid isPermaLink="false">5d3953fba332c51331d0e3a5</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Sun, 17 Sep 2017 14:40:20 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/erol-ahmed-wKTF65TcReY-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://blog.shovonhasan.com/content/images/2019/07/erol-ahmed-wKTF65TcReY-unsplash.jpg" alt="Pattern for Rendering Lists of Connected Components with React-Redux"><p>The usual pattern for rendering lists of components often ends with delegating all of the responsibilities of each child component to the entire list container component. But with a few optimizations, we can make a change in a child component not cause the parent component to re-render.</p>
<p>Let's make a list of React components go from this:</p>
<img src="https://blog.shovonhasan.com/content/images/2017/09/impl1.gif" alt="Pattern for Rendering Lists of Connected Components with React-Redux">
<p>To this:</p>
<img src="https://blog.shovonhasan.com/content/images/2017/09/impl2.gif" alt="Pattern for Rendering Lists of Connected Components with React-Redux">
<p>To be clear, <strong>the first example above doesn't actually cause wasted re-renders, according to <code>react-addons-perf</code>.</strong></p>
<p>We'll be using TypeScript (for clarity and clearly defining what data our components receive) and Immutable.js. The source code of the finished app is available <a href="https://github.com/Anveio/connected-list-components-example">on github</a> and a live demo is available <a href="https://pirate-ronald-83725.netlify.com/">here</a>.</p>
<h2 id="theproblem">The problem</h2>
<p>Let's imagine that we're building a website to list animals for adoption, and that each animal looks like this:</p>
<pre><code class="language-TypeScript">export interface Animal {
  readonly id: string;
  readonly name: string;
  readonly adopted: boolean;
  readonly type: 'Cat' | 'Dog';
}
</code></pre>
<p>Consider this <code>react-redux</code> implementation of rendering a list of DOM elements to display animals for adoption. The important stuff is in the <code>Props</code> and <code>Handlers</code> interfaces.</p>
<script src="https://gist.github.com/Anveio/866441a4b2be6cea1f00e5fdbc86fc6a.js"></script>
<p>We get most of what we need to know from the <code>Props</code> and <code>Handlers</code> interfaces: AnimalTable accepts an immutable map of Animals. We see in the <code>mapState</code> function that it gets that data from subscribing to the store's <code>animal</code> property. It also receives the dispatching function to toggle an animal's <code>adopted</code> property (which we'll just trust is implemented properly, since it doesn't matter for this example).</p>
<p>In AnimalTable's <code>render</code> method, for each of the animals in the Animal Map it renders an AnimalListing, passing it the <code>toggleStatus</code> action creator and an Animal. We can guess that an AnimalListing will contain a button to invoke <code>toggleStatus</code> and will display the information specific to its animal.</p>
<p>To summarize, AnimalTable does a lot. Without even looking at the code for AnimalListing we can guess at everything it does because <strong>AnimalTable is responsible for all of the functionality of each AnimalListing</strong>. AnimalTable doesn't even do anything with the callback its passed in, it only passes it along to each AnimalListing. And does it really need the entire map of animals, complete with the entire Animal object?</p>
<p>We can simplify this massively. Each AnimalListing can be a connected react-redux component that subscribes only to one particular animal. But how do we know which animal to give to which AnimalListing? The key is in the second, optional argument that can be passed in to the first argument of <code>connect</code> (which is idiomatically called <code>mapStateToProps</code>). The second argument of <code>mapStateToProps</code> are the props that the parent of a component passes down to a connected component, which we can call <code>OwnProps</code>.</p>
<h2 id="connectingindividualanimallistings">Connecting individual AnimalListings</h2>
<p>If AnimalTable passes down just an id to each AnimalListing, AnimalListing could use that id to subscribe to a specific animal in the store. Let's look at an AnimalListing that implements this pattern:</p>
<script src="https://gist.github.com/Anveio/a5b1d72d34d87329da68cf5aca7a85fb.js"></script>
<p>The important part here are the <code>Props</code> and <code>OwnProps</code> interfaces, and the <code>mapState</code> function. When <code>mapState</code> is called on an AnimalListing, AnimalListing already has the id that AnimalTable gives it, and we use that id to assign it a specific Animal.</p>
<p>Also notice that we were able to move the action that dispatches <code>toggleAdoption</code> to the component that actually uses it, AnimalListing.</p>
<h2 id="fixinganimaltable">Fixing AnimalTable</h2>
<p>With this pattern, AnimalTable really only needs an array of ids, so it could look like this:</p>
<script src="https://gist.github.com/Anveio/57d028ec3371e344e6ac9571a7c28d78.js"></script>
<p>Now AnimalTable receives just an immutable List of strings, which are animalIds it passes down to each AnimalListing. The only problem here is that we're doing a lot of logic in our <code>mapState</code> function, which we'll solve in the next section.</p>
<h2 id="addingreselect">Adding reselect</h2>
<p>To hide the logic we're now implementing in AnimalTable's <code>mapState</code> function, we can use the ultra-light <code>reselect</code> library.</p>
<pre><code class="language-TypeScript">
// src/selectors.ts

import { createSelector } from 'reselect';
import { RootState, Animal } from './types';

const animalsSelector = (state: RootState) =&gt; state.animals;

export const animalIdsSelector = createSelector(
  [ animalsSelector ],
  (animals) =&gt; animals.map((animal: Animal) =&gt; animal.id).toList()
);
</code></pre>
<p>And now we can use it in AnimalTable's <code>mapState</code>:</p>
<pre><code class="language-TypeScript">import { animalIdsSelector } from '../selectors';

...

const mapState = (state: RootState): Props =&gt; ({
  animalIds: animalIdsSelector(state)
});
...
</code></pre>
<p>Although it isn't doing much in this example, reselect is a valuable tool when you start sorting, filtering, and otherwise manipulating data before you pass it to a component (<a href="https://github.com/Anveio/mturk-engine/blob/8065e59232f17481eb4f033d09ed86ca552f0910/src/selectors/search.ts">here's an example from one of my own projects</a>). And if a change in one selector doesn't change the result of another, your component won't re-render.</p>
<h2 id="thefinaltouch">The final touch</h2>
<p>At this point we have implemented everything we need to leverage immutable data structures to prevent re-rendering the entire AnimalTable when we adopt a single animal: a custom <code>shouldComponentUpdate</code>.</p>
<pre><code class="language-TypeScript">class AnimalTable extends React.Component&lt;Props, never&gt; {
  shouldComponentUpdate(nextProps: Props) {
    return !nextProps.animalIds.equals(this.props.animalIds);
  }
  ...
</code></pre>
<p><code>shouldComponentUpdate</code> will return false if the props its receiving are equal to the props it already has. And because the AnimalTable is receiving just a List of string IDs, a change in the adoption status won't cause AnimalTable to receive a different set of IDs.</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Deploying a TypeScript + Node AWS Lambda Function with Serverless]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>Serverless plugins make developing Lambda apps with TypeScript painless (no webpack required!)</p>
<p>This guide assumes you have <a href="https://www.typescriptlang.org/">TypeScript</a> and <a href="https://nodejs.org/en/">Node</a> installed as well as an AWS account. We'll be using <a href="https://github.com/serverless/serverless">serverless</a> to set up our development environment and to package our app for deployment.</p>
<h1 id="frommkdirtodeploy">From <code>mkdir</code> to Deploy</h1>
<p>Let's get</p>]]></description><link>https://blog.shovonhasan.com/deploying-a-typescript-node-aws-lambda-function-with-serverless/</link><guid isPermaLink="false">5d3953fba332c51331d0e3a4</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Sun, 30 Jul 2017 20:09:49 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/taylor-van-riper-yQorCngxzwI-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://blog.shovonhasan.com/content/images/2019/07/taylor-van-riper-yQorCngxzwI-unsplash.jpg" alt="Deploying a TypeScript + Node AWS Lambda Function with Serverless"><p>Serverless plugins make developing Lambda apps with TypeScript painless (no webpack required!)</p>
<p>This guide assumes you have <a href="https://www.typescriptlang.org/">TypeScript</a> and <a href="https://nodejs.org/en/">Node</a> installed as well as an AWS account. We'll be using <a href="https://github.com/serverless/serverless">serverless</a> to set up our development environment and to package our app for deployment.</p>
<h1 id="frommkdirtodeploy">From <code>mkdir</code> to Deploy</h1>
<p>Let's get the boring stuff out of the way first. We'll install serverless and configure our AWS credentials. After that we're ready for our first deploy.</p>
<p>First, let's install the <a href="https://serverless.com/framework/docs/providers/aws/cli-reference/">serverless CLI</a>:</p>
<pre><code>npm i serverless -g
</code></pre>
<p>We can now generate the minimum deployable boilerplate for our app:</p>
<pre><code>mkdir node-typescript-lambda &amp;&amp; cd node-typescript-lambda
serverless create --template aws-nodejs
</code></pre>
<p>We now have a simple Lambda function in <code>handlers.js</code> and a <code>serverless.yml</code> which will tell serverless how to deploy our function to AWS.</p>
<p>Now let's configure our AWS credentials so we can deploy our function. If you already have an access key and secret access key in ~/.aws/credentials then you can skip this step. First, sign in to the AWS console. At the top right, click on your name to toggle the dropdown and navigate to &quot;My Security Credentials. Then on the left navigation pane, click on &quot;Users&quot; and select a user with appropriate access. Click on the &quot;Security credentials tab&quot; to bring up the pane we're interested in. Under the section &quot;Access keys&quot; click &quot;Create Acccess key&quot;</p>
<img src="https://blog.shovonhasan.com/content/images/2017/10/aws-access-keys.jpg" alt="Deploying a TypeScript + Node AWS Lambda Function with Serverless">
<p>Take note of the two keys you've generated and then run the following command in your terminal, replacing <code>YOUR_ACCESS_KEY</code> and <code>YOUR_SECRET_KEY</code> with their actual values.</p>
<pre><code>serverless config credentials --provider aws --key YOUR_ACCESS_KEY --secret YOUR_SECRET_KEY
</code></pre>
<p>You can now choose to deploy with <code>serverless deploy</code>, <strong>but be warned this will count as a request made on your AWS account, and may incur a charge</strong>.</p>
<h1 id="serverlessplugins">Serverless plugins</h1>
<p>We're going to be using two serverless plugins. <code>serverless-offline</code> will allow us to test changes to our app locally. <code>serverless-plugin-typescript</code> will automatically compile our TypeScript files down to JavaScript both when we're developing locally and when we deploy our app.</p>
<p><strong>To keep your deployment payload small, it's important to declare these plugins as dev dependencies, otherwise serverless will install them before deploying them, increasing your lambda function's size from &lt;1kB to &gt;30MB</strong></p>
<pre><code>npm init
npm i serverless-offline serverless-plugin-typescript --save-dev
</code></pre>
<p>We'll run our local environment with <code>severless offline start</code> but first we we need to edit <code>serverless.yml</code> to include the plugins we just installed.</p>
<p>Anywhere at the lowest indendation level in <code>serverless.yml</code> include these lines.</p>
<pre><code>plugins:
  - serverless-plugin-typescript
  - serverless-offline
</code></pre>
<p>If you were to remove <code>serverless-plugin-typescript</code> you would be able to start your dev server, but we'll first need a <code>tsconfig.json</code> to tell the TypeScript compiler what to do. While we're at it, let's install the type definitions for aws-lambda.</p>
<pre><code>tsc --init
npm i @types/aws-lambda --save-dev
</code></pre>
<p>You can configure your <code>tsconfig.json</code> to your personal preference, the only requirement is: <code>&quot;rootDir&quot;: &quot;./&quot;</code> so that the compiler knows to look for <code>.ts</code> files in the current directory. If you choose to move all your <code>.ts</code> files to a new folder called <code>./src</code>, for example, make sure to change the setting to <code>&quot;rootDir&quot;: &quot;./src&quot;</code>. You can also set &quot;es6&quot; as your compilation target because Lambda uses Node 6, which supports it. I've included a sample <code>tsconfig.json</code> here:</p>
<script src="https://gist.github.com/Anveio/d33197f52812a4761ae9bf844c4af47b.js"></script>
<h1 id="addingtypes">Adding Types</h1>
<p>Our <code>handler.js</code> could use a makeover. Let's rename it to <code>handlers.ts</code> and run our development server with <code>serverless offline start</code>.</p>
<p>We'll first import the relevant types from <code>'aws-lambda'</code> and then add types to each of the function's parameters as well as the <code>response</code> object.</p>
<pre><code class="language-typescript">import { Handler, Context, Callback } from 'aws-lambda';

interface HelloResponse {
  statusCode: number;
  body: string;
}

const hello: Handler = (event: any, context: Context, callback: Callback) =&gt; {
  const response: HelloResponse = {
    statusCode: 200,
    body: JSON.stringify({
      message: Math.floor(Math.random() * 10)
    })
  };

  callback(undefined, response);
};

export { hello }
</code></pre>
<p>With these type definitions, our editor will loudly warn us when we try to add a key that shouldn't exist and provide suggestions based off the type definitions.</p>
<img src="https://blog.shovonhasan.com/content/images/2017/10/handlersTS.jpg" alt="Deploying a TypeScript + Node AWS Lambda Function with Serverless">
<p>We're almost ready to deploy this test function, but first let's exclude node_modules from our <code>serverless.yml</code> so we don't deploy <code>aws-lambda</code> and all of its dependencies.</p>
<p>Anywhere at the lowest indendation level of <code>serverless.yml</code> add the following lines:</p>
<pre><code>package:
  exclude:
    - node_modules/**/*
  include:
    handler.ts
</code></pre>
<h1 id="makingourlambdafunctionanendpoint">Making Our Lambda Function an Endpoint</h1>
<p>By editing our serverless.yml once more, we can configure our Lambda function to be a visitable URL with <a href="https://aws.amazon.com/api-gateway/">AWS APIGateway</a>.</p>
<pre><code>functions:
  hello:
    handler: handler.hello

    events:
      - http:
          path: hello
          method: get
</code></pre>
<p>By adding the last four lines, we configure our <code>hello</code> Lambda function to expose the path /hello to an HTTP GET request. If we run <code>serverless deploy</code> now it will generate a URL that you can visit in your browser.</p>
<p><img src="https://blog.shovonhasan.com/content/images/2018/04/serverless-deployed.JPG" alt="Deploying a TypeScript + Node AWS Lambda Function with Serverless"></p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Time & Space Complexity of Array.sort in V8]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>If you've ever looked at the syntax for sorting an array in JavaScript, you may have wondered how it works under the hood. The <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.sort">ECMAScript Spec</a> is (intentionally, I would guess) vague about it.</p>
<blockquote>
<p>Perform an implementation-dependent sequence of calls to the [[Get]] and [[Set]] internal methods of  [...] - ECMAScript</p></blockquote>]]></description><link>https://blog.shovonhasan.com/time-space-complexity-of-array-sort-in-v8/</link><guid isPermaLink="false">5d3953fba332c51331d0e3a2</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Thu, 01 Jun 2017 21:47:00 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/mathieu-turle-33482-2.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://blog.shovonhasan.com/content/images/2019/07/mathieu-turle-33482-2.jpg" alt="Time & Space Complexity of Array.sort in V8"><p>If you've ever looked at the syntax for sorting an array in JavaScript, you may have wondered how it works under the hood. The <a href="http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.sort">ECMAScript Spec</a> is (intentionally, I would guess) vague about it.</p>
<blockquote>
<p>Perform an implementation-dependent sequence of calls to the [[Get]] and [[Set]] internal methods of  [...] - ECMAScript 2015 Specification</p>
</blockquote>
<p>So it's up to the implementation authors. Got it. Let's first take a look at how to use the <code>.sort</code> method in JavaScript, then see how V8 chooses to implement it, and analyze its time and space complexity.</p>
<h1 id="tldr">TL;DR</h1>
<p>For arrays containing <strong>10 or fewer</strong> elements, time complexity of <code>.sort</code> is <strong>O(n^2)</strong>, and space complexity is <strong>O(1)</strong>. For <strong>longer arrays</strong> time complexity is <strong>Θ(n log(n))</strong> (average case), and space complexity is <strong>O(log(n))</strong></p>
<h2 id="usingsort">Using <code>.sort</code></h2>
<p><code>.sort</code> accepts an optional callback that takes 2 parameters and returns either a negative number, a positive number, or 0. The two parameters are the two elements of the array that are being compared. If the return value is positive, the first parameter is placed after the second. If it's negative, the first parameter is placed before the second. And if it's 0, they are equal. The callback will continually execute until the array is sorted. To make it less abstract, here's two examples.</p>
<pre><code class="language-javascript">const ascending = (a, b) =&gt; return a - b;

const descending = (a, b) =&gt; return b - a; 
</code></pre>
<p>The first function will sort an array from lowest value to highest, and the second function will sort an array from highest value to lowest. In <code>.ascending</code>, the expression <code>(a - b)</code> will evaluate to a positive number if <code>a</code> is greater than <code>b</code>, so the underlying sorting algorithm knows to put <code>a</code> after <code>b</code>. The opposite is true for the <code>descending</code> function. In both functions, <code>0</code> will be the return value if <code>a</code> and <code>b</code> are equal.</p>
<pre><code class="language-javascript">const x = [4,3,5,1,9,2,7,7,2] // Our initial unsorted array
x.sort(ascending) // =&gt; [1, 2, 2, 3, 4, 5, 7, 7, 9]
x.sort(descending) // =&gt; [9, 7, 7, 5, 4, 3, 2, 2, 1]
</code></pre>
<h2 id="thev8implementation">The V8 Implementation</h2>
<p>V8 is Google's JavaScript engine that powers Chrome and Node. Their implementation is quite clever. If we go directly to the <a href="https://github.com/v8/v8/blob/master/src/js/array.js#L758">master branch of the V8 source code</a> we can see that Quick Sort is used by default. A check is made, however, to see if the length of the array to be sorted is less than or equal to 10.</p>
<pre><code class="language-javascript">function QuickSort(a, from, to) {
    var third_index = 0;
    while (true) {
      // Insertion sort is faster for short arrays.
      if (to - from &lt;= 10) {
        InsertionSort(a, from, to);
        return;
    } 
    ...
</code></pre>
<p>So the V8 engine uses Insertion Sort for super short arrays and Quick Sort for longer arrays. Interesting.</p>
<h2 id="timeandspacecomplexity">Time and Space Complexity.</h2>
<p>There's nothing magical going on in the <code>QuickSort</code> and <code>InsertionSort</code> functions in V8. <code>QuickSort</code> appears to use a simple two-way partition so its time complexity can be described as <strong>Θ(n log(n))</strong> in the average case. Quicksort's space complexity is <strong>O(log(n))</strong>.</p>
<p><code>InsertionSort</code> uses the usual nested for loop so its time complexity is <strong>O(n^2)</strong> and its space complexity is <strong>O(1)</strong> because it sorts the array in place.</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Greedy Solution to an Array Balancing Problem]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>A few weeks ago on reddit I read a question that asked for a solution to a <a href="https://www.reddit.com/r/learnprogramming/comments/64jz3m/splitting_a_number_between_n_numbers_to_make_them/">fairly simple looking array balancing problem</a>. But it turns out that a satisfactory solution isn't easy to come by, and I didn't see any offered in the comments. In fact, I'm not even</p>]]></description><link>https://blog.shovonhasan.com/greedy-solution-to-an-array-balancing-problem/</link><guid isPermaLink="false">5d3953fba332c51331d0e3a1</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Thu, 27 Apr 2017 21:46:00 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/ricardo-gomez-angel-iPQnx3rIpvo-unsplash-1.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://blog.shovonhasan.com/content/images/2019/07/ricardo-gomez-angel-iPQnx3rIpvo-unsplash-1.jpg" alt="Greedy Solution to an Array Balancing Problem"><p>A few weeks ago on reddit I read a question that asked for a solution to a <a href="https://www.reddit.com/r/learnprogramming/comments/64jz3m/splitting_a_number_between_n_numbers_to_make_them/">fairly simple looking array balancing problem</a>. But it turns out that a satisfactory solution isn't easy to come by, and I didn't see any offered in the comments. In fact, I'm not even <em>completely</em> happy with the solution I'll present in this post.</p>
<h1 id="theproblem">The problem</h1>
<p>The requirements are as follows: write a function that takes a number and divides that number among the elements of a given array such that it brings the difference between the elements to be as small as possible.</p>
<p>To make it more concrete, let's set up our test cases and our expected values. Our function will be called <code>.balance</code> and it will be added to the Array prototype:</p>
<p>Two important caveats:</p>
<ul>
<li>An element should never decrease in value to balance out the rest of the array.</li>
<li>The output should have non-whole numbers if it produces the least difference between the elements of the array.</li>
</ul>
<pre><code>[2, 3, 0].balance(5)    // =&gt; Expected output: [3.3, 3.3, 3.3]
[2, 3, 0].balance(1)    // =&gt; Expected output: [2, 3, 1]
[5, 7].balance(4)       // =&gt; Expected output: [8, 8]
[2, 0, 0, 0].balance(2) // =&gt; Expected output: [2, 0.66, 0.66, 0.66]
</code></pre>
<p>The creator of the reddit post wanted to simulate the behavior of adding liquid to a grid containing various amounts of liquid and making sure the added liquid balanced itself out.</p>
<h2 id="thequickanddirtyway">The quick and dirty way</h2>
<p>I posted my solution to the problem in the comments section <a href="https://www.reddit.com/r/learnprogramming/comments/64jz3m/splitting_a_number_between_n_numbers_to_make_them/">here</a>. A naïve (but fast) implementation that others suggested was to calculate the average value of the array if the parameter of <code>.balance</code> was added to the array, and then set every element of the array equal to that value. The suggested averaging algorithm would look like this:</p>
<pre><code class="language-javascript">Array.prototype.balance = function(input) {
  let currentSum = this.reduce((accumulator, el) =&gt; {
    { return accumulator + el }
  })
  let avg = (currentSum + input)/this.length
  return this.map(() =&gt; avg)  
}

[2, 3, 0].balance(4) // =&gt;    [3,3,3]        PASS
[2, 3, 0].balance(1) // =&gt;    [2, 2, 2]      FAIL
[5, 7].balance(4) // =&gt;       [8,8]          PASS
[2, 0, 0, 0].balance(1) // =&gt; [ 1, 1, 1, 1 ] FAIL
</code></pre>
<p>This implementation finishes in O(n) time and passes our first and third test cases but fails the second and fourth. In fact, any time the average of the array is less than any of the elements in the array, the method will fail. A more comprehensive solution is needed.</p>
<h2 id="theslowbutsuresolution">The slow but sure solution</h2>
<p>Because we're trying to distribute a value as fairly as possible among the elements of an array, we can assume that we'll always be &quot;giving&quot; to the lowest values in the array. Written out step by step, it's this:</p>
<ol>
<li> Find the lowest value in the array. </li>
<li> Find all the values in the array that have that value and store their indexes. </li>
<li> Divide 1 by the number of elements that contain the lowest value. Store that value. </li>
<li> Add the number calculated in step three to each of the elements you found in step 2. </li>
<li> Decrement the parameter by 1. </li>
<li> If the parameter is greater than 0, go to step 1.
</li></ol>
<p>Because we're making the locally optimal choice for each 'point' we're distributing among the array, this would constitute a <a href="https://en.wikipedia.org/wiki/Greedy_algorithm">greedy algorithm</a>. An implementation of this algorithm in JavaScript might look like this:</p>
<pre><code class="language-javascript">Array.prototype.balance = function(input) {
  let ret = this;

  for (let i = input; i &gt; 0; i--){
    // Find the lowest value of the array
    let lowestVal = Math.min(...ret);

    // Find indexes of lowest values in the array
    let indexesOfLowestVals = [];
    ret.map((el, index) =&gt; {
      if (el === lowestVal){
        indexesOfLowestVals.push(index);
      }
    });

    // Distribute 1 point among the lowest values equally
    let avgValue = 1/indexesOfLowestVals.length;
    indexesOfLowestVals.map(index =&gt; ret[index] += avgValue);
  }

  // Round the final elements to two decimal places and return.
  return ret.map(el =&gt; { return parseFloat(el.toFixed(2)) });
};
</code></pre>
<p>This passes the following tests:</p>
<pre><code class="language-javascript">[2, 3, 0].balance(4) // =&gt; [3,3,3]
[2, 3, 0].balance(5) // =&gt; [3.3, 3.3, 3.3]
[2, 3, 0].balance(1) // =&gt; [2,3,1]
[5, 7].balance(4) // =&gt; [8,8]
[2, 0, 0, 0].balance(2); // =&gt; [2, 0.66, 0.66, 0.66]
</code></pre>
<p>As with anything written in JavaScript you can test this method in your browser's console.</p>
<h1 id="conclusion">Conclusion</h1>
<p>This method is <strong>slow</strong>. We pass through the entire array once just to find the lowest value, then again to record the indexes that match the lowest value, and then distribute to the indexes we recorded, which could possibly be the entire array. We would do that entire process 77 times if we called <code>.balance</code> with <code>77</code>, with one additional pass through to do the rounding. I'd be interested to see a better implementation, however, even in a different language.</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Never Use Array.from() to Convert Strings to Arrays]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p><strong>TL;DR: Splitting a string into an array is about 70 times faster with <code>'a string'.split('')</code> than <code>Array.from('a string')</code>.</strong></p>
<p>In my interview prep I came across <a href="https://medium.freecodecamp.com/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb">an article on three ways of reversing a string in JavaScript</a> by Sonya Moisset. The problem of reversing a string</p>]]></description><link>https://blog.shovonhasan.com/never-use-array-from-to-convert-strings-to-arrays/</link><guid isPermaLink="false">5d3953fba332c51331d0e3a0</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Mon, 10 Apr 2017 21:44:00 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/providence-doucet-wPaBwop_rSo-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://blog.shovonhasan.com/content/images/2019/07/providence-doucet-wPaBwop_rSo-unsplash.jpg" alt="Never Use Array.from() to Convert Strings to Arrays"><p><strong>TL;DR: Splitting a string into an array is about 70 times faster with <code>'a string'.split('')</code> than <code>Array.from('a string')</code>.</strong></p>
<p>In my interview prep I came across <a href="https://medium.freecodecamp.com/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb">an article on three ways of reversing a string in JavaScript</a> by Sonya Moisset. The problem of reversing a string may seem trivial (and it is), but I'm never &quot;too good&quot; to come up with an answer for a problem. The author of the article showed three perfectly acceptable ways of reversing a string, but I'll share a fourth way that I like. I've been on a <code>.reduce</code> binge lately, and I've been thinking of ways to shoehorn it into every iterator I write, so I figure I'll do it again here.</p>
<h3 id="thenormalway">The normal way</h3>
<p>If you were a sane person confronted with the problem of reversing a string, your first instinct might be to avoid reinventing the wheel and just use the built in <code>Array.prototype.reverse</code> method. And to do that you would have to turn your string into an array so you would probably write something like this:</p>
<pre><code>String.prototype.reverseNormal = function(){  
  return this.split('').reverse().join('');
};
</code></pre>
<p>Easy and readable. If you wrote this on the whiteboard during an interview you'd probably get the nod. But what if you wanted a confused look instead?</p>
<h3 id="thereduceway">The .reduce() way</h3>
<pre>
String.prototype.reverseReduce = function(){  
  return Array.from(this).reduceRight( (prev, current) => { 
    return prev + current;
  });
};
</pre>
<p>This algorithm uses <code>Array.from</code> to convert the string into an array such that each element is a character in the string. It then calls <code>.reduceRight</code> which functions similarly to regular old <code>.reduce</code> except it iterates from right to left. Since we're not passing a second argument into <code>.reduceRight</code> to define a starting point, it will set <code>prev</code>, which is our accumulator, to the last element by default. And <code>current</code>, which is the current element at each call, will begin as the second to last element. At each call we build a reversed string through <code>return prev + current</code> by the nature of working backwards from the end of the string. Since we iterate through the array once linearly, the time complexity is O(n).</p>
<h2 id="benchmarks">Benchmarks</h2>
<p>I wont bury the lede: the reduce way is <strong>significantly</strong> slower. Benchmarks were run on a <a href="https://c9.io/">Cloud9</a> Free Workspace using <a href="https://github.com/bestiejs/benchmark.js">Benchmark.js</a> in Node v7.9.0. Each method was tested twice: once with a long string (<code>'abcdefg'.repeat(99)</code>) and once with a short string (<code>'abcdefg'</code>). Here are the results:</p>
<pre><code>String#reverseNormal Long x 39,643 ops/sec ±4.08% (73 runs sampled)
String#reverseNormal Short x 845,394 ops/sec ±3.59% (69 runs sampled)
String#reverseReduce Long x 5,955 ops/sec ±3.70% (75 runs sampled)
String#reverseReduce Short x 175,195 ops/sec ±4.40% (68 runs sampled)
Fastest is String#reverseNormal Short
</code></pre>
<p>The results are fairly clear: <strong>reversing a string the normal way is faster</strong>. The bottleneck, however, seems to be in the <code>Array.from</code> method. I set up a test suite in which the only action was splitting a string. Two tests performed it with <code>Array.from(someString)</code> and two tests performed it with <code>someString.split('')</code>. The tested strings were the same as the ones used in the previous benchmarks.</p>
<pre><code>Array#from Long x 10,322 ops/sec ±1.88% (75 runs sampled)
Array#from Short x 326,023 ops/sec ±2.11% (76 runs sampled)
String#split Long x 762,177 ops/sec ±3.33% (83 runs sampled)
String#split Short x 6,611,921 ops/sec ±2.53% (76 runs sampled)
</code></pre>
<p><code>String.prototype.split</code> is almost <strong>74 times faster</strong> than <code>Array.from</code> for converting long strings to arrays. Interestingly, if we substitute in <code>this.split</code> into the <code>String.reverseReduce</code> method instead of <code>Array.from(this)</code>, the results get a lot closer:</p>
<pre><code>String#reverseNormal Long x 27,795 ops/sec ±3.43% (69 runs sampled)
String#reverseNormal Short x 814,784 ops/sec ±5.00% (67 runs sampled)
String#reverseReduce Long x 36,910 ops/sec ±3.65% (75 runs sampled)
String#reverseReduce short x 1,061,802 ops/sec ±4.60% (68 runs sampled)
</code></pre>
<p>The two algorithms are almost equally performant when we do it this way. So the final <code>.reverseReduce</code> method looks like this:</p>
<pre><code>String.prototype.reverseReduce = function(){  
  return this.split('').reduceRight( (prev, current) =&gt; { 
    return prev + current;
  });
};
</code></pre>
<h1 id="conclusion">Conclusion</h1>
<p>Never use <code>Array.from()</code> to convert a string of any length to an array. Instead, prefer <code>String.prototype.split</code>. The <a href="https://www.ecma-international.org/ecma-262/7.0/#sec-string.prototype.split">2016 ECMAScript spec for String.prototype.split</a> and <a href="https://www.ecma-international.org/ecma-262/7.0/#sec-array.from">2016 ECMAScript spec for Array.from</a> are available here. Someone with a deeper understanding of JavaScript can probably do a much better job than I at explaining the performance disparity.</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Simulating an Ability from World of Warcraft in JavaScript]]></title><description><![CDATA[A simple approach with modern JavaScript.]]></description><link>https://blog.shovonhasan.com/simulating-an-ability-in-world-of-warcraft/</link><guid isPermaLink="false">5d3953fba332c51331d0e39f</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Fri, 31 Mar 2017 21:39:00 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/marek-brzoska--BVVXOxRGeY-unsplash.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://blog.shovonhasan.com/content/images/2019/07/marek-brzoska--BVVXOxRGeY-unsplash.jpg" alt="Simulating an Ability from World of Warcraft in JavaScript"><p>After working through Gordon Zhu's fantastic <a href="https://watchandcode.com/">&quot;Practical JavaScript&quot;</a> course, I wanted to make an app to put my newfound knowledge to the test. I like World of Warcraft, and I play an Outlaw Rogue in that game, so I created <a href="https://rollthebones.herokuapp.com">rollthebones</a>, a single page, one-button webapp.</p>
<p>If you're not familiar, <a href="http://www.wowhead.com/spell=193316/roll-the-bones">&quot;Roll the Bones&quot;</a> is an ability in the game World of Warcraft. The ability allows a player to generate some random &quot;buffs&quot; that enhance the player's character for a brief time.</p>
<h1 id="underthehood">Under the hood</h1>
<p>Roll the Bones works like this:</p>
<ul> 
<li>A numbered six sided die is rolled six times.</li>
<li>The numbers that occurred the most are kept, the others are discarded</li>
<li>The kept numbers are translated into the buffs that the players receive.</li>
</ul>
<p>To make it less abstract, imagine that your six rolls yielded these results <code>[1,1,1,2,3,4]</code>. Since <code>1</code> is the most common result, your result would just be an array containing <code>[1]</code>.</p>
<p>A few more examples:</p>
<pre><code>[1,1,2,2,3,4] =&gt; [1,2]
[4,5,4,3,5,3] =&gt; [3,4,5]
[6,2,3,4,1,5] =&gt; [1,2,3,4,5,6]
</code></pre>
<p>Those collated results would be translated to corresponding buff(s). There are six buffs, and they're all pirate themed:</p>
<ul> 
<li>"Grand Melee"</li>
<li>"Buried Treasure"</li>
<li>"Jolly Roger"</li>
<li>"Broadsides"</li>
<li>"Shark-infested Waters"</li>
<li>"True Bearing</li>
</ul>
<h1 id="simulatingaroll">Simulating a roll</h1>
<p>This behavior should be fairly simple to replicate in JavaScript. Let's set up the die first. We can skip the translation from numbers to buff-names just by making each side of the die, instead of being plain numbers, correspond to a buff-name right from the beginning. This has the added benefit of ensuring that we're working with strings the whole way through.</p>
<pre><code class="language-javascript">const BUFFS_ARRAY = [
  'Grand Melee',
  'Jolly Roger',
  'Buried Treasure',
  'Broadsides',
  'Shark Infested Waters',
  'True Bearing'
];
</code></pre>
<p>The next step is to simulate rolling the die (from now on called &quot;bones&quot;, let's be thematic). We can do that by using JavaScript's <code>.map</code> method.</p>
<pre><code class="language-javascript">const rawRoll = () =&gt;
  BUFFS_ARRAY.map(
    () =&gt; BUFFS_ARRAY[Math.floor(Math.random() * BUFFS_ARRAY.length)]
  );
}
</code></pre>
<p>The code above independently samples a random element from <code>BUFFS_ARRAY</code> 6 times into a new array. It generates a random number between 0 and 5 and returns the element of <code>BUFFS_ARRAY</code> at that index. It does this <code>BUFFS_ARRAY.length</code> times because we're running <code>.map</code> which iterates through an array and returns a new one.</p>
<h1 id="generatingahistogram">Generating a histogram</h1>
<p>The next step is to find out which value occurs most. We can do that in two parts. The first step is to generate a histogram object where each key is a buff name and each value is the number of times that buff occurred in our <code>rawRoll</code> array.</p>
<pre><code class="language-javascript">const generateHistogram = (ary) =&gt; {
  return ary.reduce((counter, el) =&gt; {
    counter[el] = counter[el] ? counter[el] + 1 : 1;
    return counter;
  }, {})
}
</code></pre>
<p><code>ary</code> in our case will always be a six item array containing only strings that we create with <code>rawRoll();</code>.</p>
<p>Since we're taking an array and making an object out of it, <code>.reduce</code> will fit our needs perfectly. We provide <code>{}</code> as the last parameter to make an empty object the starting point for counter. Then, for each element in the given array, if the element does not exist as a key in our counter object, we create a key and assign it a value of one, letting us know that the element has occurred once so far. Otherwise we simply increment the value of that key by 1 to account for the fact that it has shown up again.</p>
<h1 id="recap">Recap</h1>
<p>Let's recap. At this point we can roll the bones six times and generate a histogram of how often we get each buff. If we call <code>rawRoll();</code> in our browser's console we might get something like this:</p>
<pre><code class="language-javascript">let x = rawRoll();
Array [ &quot;Shark Infested Waters&quot;, &quot;True Bearing&quot;, &quot;True Bearing&quot;, &quot;True Bearing&quot;, &quot;Jolly Roger&quot;, &quot;Grand Melee&quot; ]
</code></pre>
<p>And if we call <code>generateHistogram();</code> on that array we end up with an object that looks like this:</p>
<pre><code class="language-javascript">generateHistogram(x)
Object { Shark Infested Waters: 1, True Bearing: 3, Jolly Roger: 1, Grand Melee: 1 }
</code></pre>
<p>If these are our results, then our character would end up with a single buff called &quot;True Bearing&quot; (which is the best one by the way) because it occurred most frequently. We haven't programmed that part yet though, so the next and final step is to keep only the buffs that occurred most often.</p>
<h1 id="findingthemodes">Finding the modes</h1>
<p>Let's write a method to find the modal values of the object and return the corresponding keys.</p>
<pre><code class="language-javascript">const findModes = (histogram) =&gt; {
  const mode = Math.max(...Object.values(histogram))
  return Object.keys(histogram).filter(el =&gt; histogram[el] == mode)
}
</code></pre>
<p>In this case the triple dot <code>...</code> is the spread operator, not the rest operator. Math.max accepts comma separated arguments, each of which is a number, and returns the highest number. We use it here to spread the array of numbers from our histogram's values as the argument to Math.max. This will give us the modal value of our histogram.</p>
<p>We use that modal value to determine which keys (which are at strings like &quot;True Bearing&quot; or &quot;Jolly Roger&quot; or &quot;Grand Melee&quot; etc.) correspond to a frequency that equals that modal value. We filter out the buffs that don't occur the most and keep the ones that do, giving us our final result.</p>
<p>After speaking with a user on the <a href="https://discordapp.com/invite/9zT7NHP">r/learnprogramming discord</a>, I was shown a different implementation.</p>
<pre><code class="language-javascript">let max = -1;
let keys = [];

Object.keys(histogram).forEach(key =&gt; {
    if (histogram[key] &gt; max) {
        max = histogram[key];
        keys = [key];
    } else if (histogram[key] === max) {
        keys.push(key);
    }
});
</code></pre>
<p>I like this implementation a lot. Whereas mine iterated through the given histogram object twice (once to determine the max value, and once to filter out the unwanted keys), the other implementation runs through the histogram a single time, changing the <code>max</code> value and emptying the <code>keys</code> array as necessary. This implementation would be better if we're feeding <code>findModes</code> very very large histograms but for my purposes I'm deciding to stick with my implementation because it's easier to read and correctly guess the purpose of. There's also an imaginary &quot;worst-case&quot; scenario for this implementation in which, because <code>modes</code> might change constantly, the <code>keys</code> array might also constantly be being appended to, emptied, and remade. Additionally, this implementation won't work for histograms containing only negative numbers.</p>
<h3 id="wrappingitup">Wrapping it up</h3>
<p>We now have everything we need to simulate the Roll the Bones ability. And in doing so we were able to apply our knowledge of the three most common functional programming methods in JavaScript: <code>.map</code>, <code>.filter</code>, and <code>.reduce</code>.</p>
<p>Since we only care about the final result of Rolling the Bones and don't care about the underlying functionality, all we need now is a function to abstract away all the little stuff.</p>
<pre><code class="language-javascript">const generateRoll = () =&gt; return (findModes(generateHistogram(rawRoll())))
</code></pre>
<p>That many parentheses always makes me nervous. But now that we've successfully created the core functionality of rolling the bones, everything else will follow.</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[The First Step]]></title><description><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><p>It seems natural to me that the first post on my programming blog should be how I got the blog up and running. I started with a clear vision in mind: I wanted a clean, professional looking personal website to show off my growing portfolio and to blog about my</p>]]></description><link>https://blog.shovonhasan.com/the-first-step/</link><guid isPermaLink="false">5d3953fba332c51331d0e39e</guid><dc:creator><![CDATA[Shovon Hasan]]></dc:creator><pubDate>Thu, 30 Mar 2017 21:36:00 GMT</pubDate><media:content url="https://blog.shovonhasan.com/content/images/2019/07/sebastian-unrau-CoD2Q92UaEg-unsplash-1-.jpg" medium="image"/><content:encoded><![CDATA[<!--kg-card-begin: markdown--><!--kg-card-begin: markdown--><img src="https://blog.shovonhasan.com/content/images/2019/07/sebastian-unrau-CoD2Q92UaEg-unsplash-1-.jpg" alt="The First Step"><p>It seems natural to me that the first post on my programming blog should be how I got the blog up and running. I started with a clear vision in mind: I wanted a clean, professional looking personal website to show off my growing portfolio and to blog about my growth as a developer.</p>
<h1 id="whynow">Why now?</h1>
<p>I think many people my age didn't take the internet very seriously growing up. The internet was, in my perspective, still young and mostly the territory of  nerdy teenagers and 20-somethings. Sure, some people used it for serious, professional purposes but those were stinky <em>adults</em>. Most of what I used the internet for in my teenage years was hanging around forums with other teenagers pretending to be in their 20s. I swapped from website to website as my interests changed, using different identities and personas for each one, always making sure not to leave a trail of bread crumbs from one username to another. I was a consumer, devouring media and the words of people much smarter than me in the form of blog posts and long reddit comments.</p>
<p>But I didn't want to just be a consumer anymore. I wanted to build things. Making this blog, in a real sense, is making my mark on the internet. I'm no longer an anonymous internet nomad moving from website to website. For the first time, I'm accountable for every word I write. And they won't just belong to AnonymousUser123 and be doomed to archival in shuttered forums and reddit threads. They'll have a voice and a face behind them.</p>
<h1 id="choosingghost">Choosing Ghost</h1>
<p>So I understood the problem and I understood my goals. The next step is deciding on the path I would take and the technologies I would use. I'd heard a lot of buzz about Ghost as a publishing technology but I was absolutely convinced after reading <a href="https://www.indiehackers.com/businesses/ghost">Ghost's founder John O'Nolan's interview on IndieHackers.</a> I needed to use Ghost. I loved their goals, I loved the fact that they were non-profit, and I was blown away by my experience using Ghost during my free trial of Ghost Pro. The editor just made <strong>sense</strong>. And if I was gonna spend hours writing blogs posts this is how I would want to do it.</p>
<p>Using Ghost was also a fantastic opportunity to start learning Node.js. I had originally been reticent to do so but my recent foray into Vue.js left me hungry to learn more JavaScript and I was impressed by the sample Node app that Cloud9 starts you with when you make a Node workspace: a working live chat app written in just a few files.</p>
<p>I wanted to keep it simple and free as I dip my toes into Node so I figured I could keep with my usual M.O. of using Cloud9 for my development environment and Heroku for deployment. I want to give a special thanks to Cloud9 for their excellent documentation and <a href="http://www.autodidacts.io/host-a-ghost-blog-on-heroku/">autodidacts.io</a> for their tutorial on configuring node to work with Heroku PostgreSQL. I would have never figured out any of that on my own.</p>
<h1 id="installingghost">Installing Ghost</h1>
<p>Ghost is very clear that they put their full support behind Node.js v4 so I figured I would just pick a version in that generation. Fortunately Cloud9 has <code>nvm</code> built in.</p>
<p>In our Cloud9 terminal:</p>
<pre><code>$ nvm install 4.7.3
$ nvm use 4.7.3
$ node -v
v4.7.3
</code></pre>
<p>Now it's time to download ghost and get started.</p>
<pre><code>$ curl  -L https://ghost.org/zip/ghost-latest.zip -o ghost.zip
$ unzip  -up ghost.zip -d
$ npm install --production
$ rm ghost.zip
</code></pre>
<p>Since we're running it on Cloud9 and not on a local machine, we'll have to edit <code>config.js</code> (rename <code>config.example.js</code> to <code>config.js</code> if <code>config.js</code> is missing).</p>
<pre><code>config: {
    development: {
        url: 'https://' + process.env.C9_HOSTNAME,
    },
    server: {
        host: process.env.IP,
        port: process.env.PORT
    }
}
</code></pre>
<p>We should now be able to access the blog in our development environment just by running <code>npm start</code> in our terminal.</p>
<h1 id="creatingtheblog">Creating the blog</h1>
<p>Next up is getting it ready for deployment with Heroku. First we'll need to get the right files ready in git.</p>
<pre><code>$ git init
$ git add -A
$ git commit -m &quot;First commit&quot;
</code></pre>
<p>For quality of life purposes we'll add a <code>.gitignore</code> that prevents the very large node_modules folder from being tracked so we can save some time each time we deploy.</p>
<pre><code>$ sudo echo node_modules &gt; .gitignore
</code></pre>
<p>Now it's time to make the app.</p>
<pre><code>$ heroku create name-of-app
</code></pre>
<p>Whatever <code>name-of-app</code> is will be the url of your blog. For example <code>heroku create shovonhasan</code> will make <code>shovonhasan.herokuapp.com</code>.</p>
<h1 id="settinguppostgresql">Setting up PostgreSQL</h1>
<p>The trickiest part of this whole process is setting up the database. Ghost's default setting is SQLite which doesn't work well with Heroku. So we'll use PostgreSQL instead.</p>
<pre><code>$ heroku addons:add heroku-postgresql:hobby-dev --app name-of-app
</code></pre>
<p>You could have substituted <code>hobby-dev</code> with whatever tier of the addon you're using. <code>hobby-dev</code> is just the free version. Take note of the name of the database that was just created. You'll need it for this next step.</p>
<p>The next step is a little annoying. You'll have to go to <a href="https://data.heroku.com/">Heroku's Database dashboard</a> Find the database you just created, scroll down and hit the button that says &quot;View Credentials...&quot;. Then use the information there to type the next few commands.</p>
<pre><code>$ heroku config:set POSTGRES_DATABASE=&lt;value&gt;  
$ heroku config:set POSTGRES_HOST=&lt;value&gt;  
$ heroku config:set POSTGRES_PASSWORD=&lt;value&gt;  
$ heroku config:set POSTGRES_USER=&lt;value&gt;  
$ heroku config:set MY_URL=http://your-url.com  
$ heroku config:set NODE_ENV=production  
</code></pre>
<h1 id="configuringthingsforproduction">Configuring things for production</h1>
<p>With the database out of the way we need to get our configurations for our production environment correct. In <code>config.js</code> edit the line</p>
<pre><code>production : {
  url: 'http://my-ghost-blog.com',  
</code></pre>
<p>to</p>
<pre><code>production: {
        url: 'http://name-of-app.herokuapp.com',
        fileStorage: false,
</code></pre>
<p>Make sure the url is the actual url of <em>your</em> website. In my case it was <code>'http://shovonhasan.herokuapp.com'</code>.<br>
Just a few lines below that you'll have your database settings.</p>
<pre><code>database: {  
  client: 'sqlite3',
  connection: {
    filename: path.join(__dirname, '/content/data/ghost.db')
  },
  debug: false
},
</code></pre>
<p>Since we're not using SQLite anymore we'll have to change that to:</p>
<pre><code class="language-JavaScript">database: {  
  client: 'postgres',
  connection: {
    host: process.env.POSTGRES_HOST,
    user: process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    database: process.env.POSTGRES_DATABASE,
    port: '5432'
  },
  debug: false
},
</code></pre>
<p>And then change the server settings from the default</p>
<pre><code>server: {  
  host: '127.0.0.1',
  port: '2368'
}
</code></pre>
<p>to</p>
<pre><code>server: {  
  host: '0.0.0.0',
  port: process.env.PORT
}
</code></pre>
<p>Lastly we'll need to make a <code>Procfile</code> to tell Heroku to use the new production settings we just made.</p>
<pre><code>$ echo &quot;web: NODE_ENV=production node index.js&quot; &gt; Procfile  
</code></pre>
<h1 id="deploy">Deploy</h1>
<p>In theory, we should be ready to deploy our application to Heroku.</p>
<pre><code>git add -A 
git commit -m &quot;Configure for Heroku + PostgreSQL&quot;  
git push heroku master
heroku run npm install --production
</code></pre>
<p>In my case, however, I got a silly error telling me that my version of Node was unsupported. This seems to be a common problem. If it happens to you just run</p>
<pre><code>$ heroku config:set GHOST_NODE_VERSION_CHECK=false
</code></pre>
<p>and deploy again.</p>
<h1 id="lookingforward">Looking forward</h1>
<p>Although I didn't actually write any Node code it's a nice confidence boost to be up and running with a good looking website in such a small amount of time. I'm super excited to learn more about Node and blog about my progress. I also wish I had done this sooner so I could have written about learning Vue.js while making <code>rollthebones.herokuapp.com</code>. I'm glad I at least did it now, though, because there's still so much more to learn.</p>
<!--kg-card-end: markdown--><!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>