<?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 Justin Calleja on Medium]]></title>
        <description><![CDATA[Stories by Justin Calleja on Medium]]></description>
        <link>https://medium.com/@calleja.justin?source=rss-4f0e08b23b2e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ph4EHtAfMJr_hwO9S0DsAQ.png</url>
            <title>Stories by Justin Calleja on Medium</title>
            <link>https://medium.com/@calleja.justin?source=rss-4f0e08b23b2e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:48:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@calleja.justin/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[Using plain pg with Nest.js]]></title>
            <link>https://medium.com/@calleja.justin/using-plain-pg-with-nest-js-617ec32ec2c4?source=rss-4f0e08b23b2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/617ec32ec2c4</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node-postgres]]></category>
            <category><![CDATA[gps]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Justin Calleja]]></dc:creator>
            <pubDate>Sun, 02 Feb 2020 19:58:35 GMT</pubDate>
            <atom:updated>2020-02-02T20:11:09.943Z</atom:updated>
            <content:encoded><![CDATA[<p>This is going to be a quick demo of how to get started using plain <a href="https://node-postgres.com/">pg (node-postgres)</a> with <a href="https://nestjs.com/">Nest.js</a> — no ORMs in sight. Having found no simple guide on how to do this when I was looking for it — I figured it’d be worth writing about.</p><h4>Demo on Github:</h4><p><a href="https://github.com/justin-calleja/nest-pg-demo">https://github.com/justin-calleja/nest-pg-demo</a></p><h4>Create a new Nest.js app — install pg — generate db module</h4><pre>npx nest new nest-pg-demo<br>cd nest-pg-demo<br>npm i pg<br>npx nest g module db</pre><h4>Register a Provider</h4><p>We’ll use a constants.ts file in /src to be able to import the <a href="https://docs.nestjs.com/fundamentals/custom-providers#di-fundamentals">DI token</a> for our postgres connection (or pool of connections):</p><pre>// src/constants.ts<br>export const PG_CONNECTION = &#39;PG_CONNECTION&#39;;</pre><p>The DI token (dependency injection token) is how you’ll declaratively tell the I<a href="https://en.wikipedia.org/wiki/Inversion_of_control">nversion of Control (IoC)</a> container which dependency you’d like injected. So you’ll use it to pull in a dependency from the container.</p><p>You’ll also use it when you register a provider with the container. Registering a provider is basically associating a DI token (which will be a string in our case) with a way to get a dependency. The container will use this “way to get a dependency” when you request the relevant dependency be injected.</p><p>Registering a provider looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQKMomlma1H3BZe4ImbxiQ.png" /></figure><p>i.e. we need an object with the DI token and the way to get the dependency — the dbProvider — and pass it to <strong>providers</strong> in the Module configuration as shown above.</p><p>There’s a couple of ways to specify how to get the dependency in Nest.js. We’ll be using <a href="https://docs.nestjs.com/fundamentals/custom-providers#value-providers-usevalue"><strong>useValue</strong></a>:</p><pre>import { Pool } from &#39;pg&#39;;</pre><pre>const dbProvider = {<br>  provide: PG_CONNECTION,<br>  useValue: new Pool({<br>    user: &#39;postgres&#39;,<br>    host: &#39;localhost&#39;,<br>    database: &#39;somedb&#39;,<br>    password: &#39;meh&#39;,<br>    port: 5432,<br>  }),<br>};</pre><p>Finally, we’ll also include the dbProvider in the DbModule’s exports so we’ll be able to use it in other modules importing DbModule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ZSKfUi2fss-E82Q2nKmWw.png" /></figure><h4>Use the Provider</h4><p>You’ll notice that the <strong>AppModule</strong> is already importing <strong>DbModule</strong> (at least if you generated DbModule with the nest cli that should be the case):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4B4991mXzEORr1mioh1lg.png" /></figure><p>This means that — in our AppModule i.e. in e.g. controllers and providers defined as part of AppModule) we’ll be able to ask Nest’s IoC container to inject a connection for us using the <strong>PG_CONNECTION</strong> DI token (string).</p><p>Doing so in our <strong>AppService</strong> looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xr2RwBA3Katco22d66h-Sw.png" /></figure><p>You’ll notice that we annotate conn with Injectand make it privatein the constructor. This is significant at it allows Nest to know that <strong>it</strong> should be the one to supply a value for conn and it also knows what to inject via the DI token.</p><p>getUsers is just a simple query to use as a sanity check. We’ll use it in <strong>AppController</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8sGLMsEVYTsSfS5RAOQtg.png" /></figure><p>I guess you might be wondering how we’re able to inject <strong>AppService</strong> here without the Inject annotation… That’s thanks to a shortcut (or “syntactic sugar” if you prefer). In Nest.js, registering a Provider with a class name:</p><pre>import { AppService } from &#39;./app.service&#39;;</pre><pre><a href="http://twitter.com/Module">@Module</a>({<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>… is equivalent to:</p><pre>import { AppService } from &#39;./app.service&#39;;</pre><pre><a href="http://twitter.com/Module">@Module</a>({<br>  providers: [{<br>    provider: AppService,<br>    useClass: AppService,<br>  }],<br>})<br>export class AppModule {}</pre><p>… which means — the DI token doesn’t have to be a string and now Nest.js knows what to inject when we type the private appService in <strong>AppController</strong> with the type <strong>AppService</strong>.</p><h4>Start and seed postgres</h4><p>Of course, you’re going to want postgres running if you want to try this out. If you have docker installed, take a look at the <strong>scripts</strong> and <strong>sql</strong> directories in the <a href="https://github.com/justin-calleja/nest-pg-demo">repo</a> for this demo — but the gist is:</p><pre>#!/bin/bash</pre><pre>docker run --rm \<br>    --name somedb \<br>    -e POSTGRES_PASSWORD=meh \<br>    -e POSTGRES_USER=postgres \<br>    -e POSTGRES_DB=somedb \<br>    -p 5432:5432 \<br>    -v somedb-vol:/var/lib/postgresql/data \<br>    postgres</pre><p><strong>scripts/start-db.sh</strong> starts postgres. --rm will remove the container when we stop it. By virtue of passing in the env vars we do — the container will auto create the somedb database. The volume mapping is so we keep our data even when we stop the container (and have it auto-removed).</p><p>After the db is up — you can run <strong>scripts/sync-db.sh</strong>:</p><pre>#!/bin/bash</pre><pre>SCRIPTS_DIR=`dirname &quot;$0&quot;`</pre><pre>cat &quot;$SCRIPTS_DIR/../sql/schema.sql&quot; &quot;$SCRIPTS_DIR/../sql/dev-seeds.sql&quot; \<br>    | psql -U postgres -d somedb -p 5432 -h localhost -1 -f -</pre><p>This should work regardless of your pwd when you run the script since we’re referencing the sql files relative to the location of the sync-db.sh file on disk (consider this to be an equivalent of __dirname in Node.js). Since schema.sql drops and re-creates the public schema every time — it’s safe to re-run sync-db.sh when you change your table definitions etc…</p><h4>Start the app and GET /users</h4><p>Finally, it’s time to run our app with npm run start:dev and hit the /users endpoint with:</p><pre>curl localhost:3000/users<br>[{&quot;id&quot;:1,&quot;email&quot;:&quot;<a href="/service/mailto:tmp@gmail.com">tmp@gmail.com</a>&quot;},{&quot;id&quot;:2,&quot;email&quot;:&quot;<a href="/service/mailto:user@gmail.com">user@gmail.com</a>&quot;},{&quot;id&quot;:3,&quot;email&quot;:&quot;<a href="/service/mailto:anotheruser@gmail.com">anotheruser@gmail.com</a>&quot;}]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=617ec32ec2c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with js-csp — part 2]]></title>
            <link>https://medium.com/@calleja.justin/getting-started-with-js-csp-part-2-35e7e650a57f?source=rss-4f0e08b23b2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/35e7e650a57f</guid>
            <category><![CDATA[js-csp]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[csp]]></category>
            <dc:creator><![CDATA[Justin Calleja]]></dc:creator>
            <pubDate>Sat, 27 May 2017 14:51:13 GMT</pubDate>
            <atom:updated>2017-05-27T14:51:13.360Z</atom:updated>
            <content:encoded><![CDATA[<p>Perviously, in <a href="https://medium.com/@calleja.justin/getting-started-with-js-csp-232548ef94ce">part 1</a> we took a look at how to work with the basics of js-csp in the context of writing a small CLI app. After writing the thing and stepping back a bit — I realised that, although I had split the problem up into nice understandable parts — nothing was happening concurrently. This post addresses that issue. (btw — if you’re interested in getting some practice, I’d suggest trying to do this yourself after reading the recap in the intro here).</p><p>Lets recap some of the main points we covered in part 1:</p><ol><li>yield csp.take(channel) can be used to suspend execution of a generator function and wait for a message to be available on channel before resuming. <em>Can only be used in a generator function executed by </em><em>csp.go .</em></li><li>yield csp.put(channel, msg) can be used to suspend execution of a generator function and wait for a message to be consumed from channel before resuming the generator function. <em>Can only be used in a generator function executed by </em><em>csp.go .</em></li><li>const channel = csp.go(function * () { … }) can be used to run a generator function (containing put / take ops). It returns a channel which will receive one message. This message will be whatever the generator function returns when it’s done.</li></ol><p>Now, let me spell out why the code in part 1 has no concurrency in it. I didn’t go into this previously as an exercise for the reader (ok I was also tired and didn’t feel like haha but really if you did figure it out by yourself then you certainly did understand the code):</p><ul><li>We first make a request for all contributors (this is an un-paginated result). We cannot do anything productive while we wait for this HTTP request as we need the contributors to continue.</li><li>Once we get the contributors, this is what I was doing:</li></ul><pre>const { json } = msg<br>for (let i = 0; i &lt; json.length; i++) {<br>  const contributor = json[i]<br>  yield csp.put(<br>    channels.outputCh,<br>    AddContributor(contributor.login, contributor.html_url)<br>  )<br>  const doneCh = csp.go(<br>    followerProcess,<br>    [contributor.followers_url, contributor.login, csp.chan()]<br>  )<br>  yield csp.take(doneCh)<br>}<br>return yield csp.put(channels.outputCh, FlushMsg())</pre><p>i.e. for every contributor, I was adding that contributor to the output and spawning another process to take care of fetching the contributor’s followers. I was then waiting for this process to finish before looping on to the next contributor. I was doing this because I needed to know when all followers were processed so that I could send the FlushMsg .</p><p>This, however, is the main thing that’s slowing everything down. We clearly don’t need to wait for one contributor’s followers to be fetched and added before requesting another one. (One thing to note though: I do want the contributor to be added to the output <strong>before</strong> fetching any of its followers. The reason being is that adding a follower depends on it’s contributor to have been added first (otherwise there’s no key to append to in the output)).</p><p>So that’s the problem we’ll be solving in this part… and it’s almost a one liner.</p><h4>One possible solution</h4><p>We can just collect all channels returns by spawning all followerProcesses and then wait for all of them to finish:</p><pre>let doneChs = []<br>for (let i = 0; i &lt; json.length; i++) {<br>  const contributor = json[i]<br>  yield csp.put(<br>    outputCh,<br>    AddContributor(contributor.login, contributor.html_url)<br>  )<br>  doneChs.push(<br>    csp.go(<br>      followerProcess,<br>      [contributor.followers_url, contributor.login, csp.chan()]<br>    )<br>  )<br>}</pre><pre>for (let doneCh of doneChs) { yield doneCh }</pre><pre>// all followerProcesses have ended<br>return yield csp.put(outputCh, FlushMsg())</pre><p>One thing I avoided to mention in part 1 (but now thing you’ve got enough experience to start shortening things) is that yielding a channel is equivalent to taking from it so the following are identical:</p><ul><li>yield doneCh</li><li>yield csp.take(doneCh)</li></ul><h4>Why are you switching to `for of` now?</h4><p>You might have noticed that I’m finally using the for of construct for iteration in this 2 part post. The reason is that, while writing part 1, I was getting some errors with the for of which I wasn’t getting with a plain for loop. In any case, I decided to scrap them altogether for the time being.</p><p>In particular, the reason why I’m pointing this out here is to highlight something I forgot to mention in part 1. Basically, avoid using .forEach to iterate over your collections — or any other construct that requires you to pass a callback function. The reason being that any code you write in your callback will be <strong>outside the wrapping generator function</strong> and you will no longer be able to csp.take / put .</p><h4>Check out the refactored code</h4><p>I’ve refactored the code (split in multiple files) and added the little tweak above<a href="https://github.com/justin-calleja/github-cf/tree/post2"> in branch </a><a href="https://github.com/justin-calleja/github-cf/tree/post2">post2 here</a>.</p><h4>Time?</h4><p>I ran against ubulonton/js-csp again and the <a href="https://linux.die.net/man/1/time">total time</a> came in at 38s… a marked improvement from the previous 1m 35s.</p><p>I noticed that the result wasn’t exactly the same though — the project now has one <strong>less</strong> contributor… wasn’t aware that contributor counts can go down… That said, the total lines in the output is close enough.</p><p>In any case, that’s all I got for this time. Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35e7e650a57f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with js-csp]]></title>
            <link>https://medium.com/@calleja.justin/getting-started-with-js-csp-232548ef94ce?source=rss-4f0e08b23b2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/232548ef94ce</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js-csp]]></category>
            <category><![CDATA[csp]]></category>
            <dc:creator><![CDATA[Justin Calleja]]></dc:creator>
            <pubDate>Sun, 21 May 2017 16:18:07 GMT</pubDate>
            <atom:updated>2017-05-27T14:52:38.143Z</atom:updated>
            <content:encoded><![CDATA[<p>The TLDR of CSP (Concurrent Sequential Processes) is that it’s another way of modelling concurrency just like other models you might be familiar with — e.g. using Observables in <a href="http://reactivex.io/">ReactiveX</a> implementations; Promises; or even callbacks (which I believe is a.k.a CPS (Continuation Passing Style)).</p><p>CSP uses a message passing style of communicating between processes. “Processes in JS!?” you might say — sure we might not be running more than one thread at a time, but the single thread we are running is typically in no shortage of asynchronous concerns to deal with — something CSP can help us out with.</p><p>Perhaps, in the context of JS, “communicating between <a href="http://2ality.com/2015/03/es6-generators.html">generator</a> <a href="https://davidwalsh.name/es6-generators">functions</a>” might be easier to follow.</p><p>In any case:</p><blockquote>I hear and I forget. I see and I remember. I do and I understand. — Confucius</blockquote><p>There… I can feel my beard growing longer already…</p><h3>App requirements</h3><p>We’ll be talking about CSP in the context of an example CLI app. Which means… this might not be the most focused discussion of CSP you’ll come across. But hey, my editor approves it (pats self on back).</p><p>We’ll be going through most of the code here but not entirely, so checkout the <a href="https://github.com/justin-calleja/github-cf">repo on Github</a>.</p><p>We want:</p><ul><li>Given: Github owner, Github repo, your Github username, your Github password</li><li>Output: a JSON document with all contributors of the selected repository (i.e. the given owner + repo), as well as all followers of each contributor of said repository.</li></ul><p>Some things to note:</p><ul><li>We need to exhaust Github’s pagination for the followers API.</li><li>We need to buffer found results in memory (as opposed to spitting data out ASAP), since we also want to do some head counting and make a record of totals in our output JSON.</li><li>We will only console.log the output JSON so we can re-direct the program’s stdout to a file. Errors can use console.error.</li></ul><p>Another thing to note is that you might want to put the following in your .bash_profile (or similar):</p><pre>export HISTCONTROL=ignorespace</pre><p>That way, you’ll be able to prefix any commands you run through your shell with a space and have that command omitted from your history. (Of course, you might want to check if your shell actually supports this — I’m running zsh, but this should work fine for bash too).</p><p>Now you can export your Github password as an environment variable (GITHUB_PASS) once (prefixed by a space); not have that stored in your history; and not have to supply it every time to our CLI app (running the risk of forgetting to whitespace prefix <em>that</em> command) — phew… that was a lot shorter to explain in my mind…</p><h3>Channels and processes</h3><p>In CSP, we pass messages through channels. Unlike message passing in some other models of concurrency (like the Actor model), channels are not a simple “fire and forget” mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*MexgeXhURcLK1zpm2zAlbA.jpeg" /></figure><p>… and walk away from it. Think:</p><ul><li>Phoning someone and waiting for them to pick up to tell them a message (synchronous message passing)</li><li>V.s. sending them an email (asynchronous message passing)</li></ul><p>Another way you’ll hear this put is that channels come with “back pressure” built-in. Through back pressure, a channel’s consumer can communicate it’s readiness for consumption to the channel’s producer — which in turn can stop producing messages until the consumer is ready.</p><p><em>(Note: there are variations to this (like buffered channels) — but we’ll only be covering the basics here).</em></p><p>That’s pretty much all we need to know about CSP to start using it. Lets now have a look at our app’s processes and the channels they’ll be using.</p><h4>Request process</h4><p>We’ll have one process solely dedicated to making HTTP requests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65e2b5124d6e2fbda979cc769bb892da/href">https://medium.com/media/65e2b5124d6e2fbda979cc769bb892da/href</a></iframe><ul><li>We’re using an infinite loop (a common pattern when programming with generators) to csp.take messages from a requestCh channel. This operation blocks until there is a message on the channel. That doesn’t mean it blocks our single thread (our program). We’re yielding out of this generator function allowing anything else on the event loop to execute.</li><li>We’re checking we got the right kind of message (more on this later).</li><li>Using the message’s content, we’re making an HTTP request and replying back on the given successCh channel with the parsed JSON we got back from Github’s API.</li></ul><h4>Contributor process</h4><p>Another process will handle what to do with the response from the “get me all contributors request”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27cf771c2933bd71aff8813e36e2aefd/href">https://medium.com/media/27cf771c2933bd71aff8813e36e2aefd/href</a></iframe><ul><li>I only skimmed the Github API but I saw no reference to pagination there, so I’m assuming the contributors request gets us all contributors.</li><li>We’re taking a message from the channel (put there by the requestProcess) and for each contributor in the JSON response, we’re adding the contributor to our output by sending another message to the outputCh .</li><li>We’re “spawning” another process (i.e. running a generator function) to handle getting the contributor’s followers. Apart from the initial URL to fetch a given contributor’s followers from (and the contributor’s login name), we’re also passing this new process a dedicated channel it can use to communicate with requestProcess .</li><li>Notice that spawning a new process gives us back another channel (doneCh). This channel receives the process’s return value. Since we’re take ing from this channel… it’s kind of important that our followerProcess generator function actually returns a value (and not loop infinitely) as that will unblock the contributorProcess and allow it to process the next contributor.</li><li>Once all contributors are processed (and, because of the way we set it up — all followers too), we’re ready to put a FlushMsg on our outputCh to stdout our JSON.</li></ul><h4>Follower process</h4><p>The followerProcess below will be spawned for each contributor and it’s purpose will be to request all followers for a given contributor (exhausting pagination):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cddc249a429be88cddf9d19a205f8c86/href">https://medium.com/media/cddc249a429be88cddf9d19a205f8c86/href</a></iframe><ul><li>Right off the bat we put a message on requestCh to make an HTTP request and get our first page of followers.</li><li>Again, we enter an infinite loop… but remember, unlike the requestProcess , we must eventually exit this loop as the contributorProcess is waiting for a done signal on the doneCh . However, since we don’t know how many pages we’ll be requesting, we start off in an infinite loop.</li><li>After getting our JSON back, we send all followers to the outputProcess .</li><li>We check for the existence of the Link header in the response. If it exists we must put another message on the requestCh to make our next HTTP request. Otherwise, we’ll just return since we’re done paginating. Returning ends the generator function and the doneCh returned by csp.go in our contributorProcess gets a message (supposedly undefined since we’re not returning a value here).</li></ul><h4>Output process</h4><p>Our final process, outputProcess is responsible for buffering all collected values and outputting our result when we tell it to. If you’re familiar with Redux, you should be pretty familiar with what’s going on:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16912c0987d8992d50471a6b1661495e/href">https://medium.com/media/16912c0987d8992d50471a6b1661495e/href</a></iframe><ul><li>We define our initial state and enter an infinite loop (since we don’t know how many messages we’ll be processing).</li><li>The idea then is to wait for messages and change the state accordingly. The reducers (which change our state) are not included here as they’re not quite relevant to the subject matter (see final code).</li><li>Upon receiving a FlushMsg we make our final reduction to our state (to add totals to the output JSON) and console.log .</li></ul><h3>Our messages are some type of sum types — ye?</h3><p>When sending messages around, it stands to reason that you want to be able to distinguish between different types of messages. You might be familiar with the use of the action field in Redux messages — or some other ad-hoc way of tagging your messages. That’s cool — it works (even Erlang uses it).</p><p>However, I have a preference for using <a href="https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/sum-types">sum types</a> if at all possible. JS doesn’t have (static) types, so we’ll be using the nifty <a href="https://www.npmjs.com/package/daggy">daggy</a> npm package to simulate them.</p><p>Why? Because I want to be able to create enumeration of messages, each with their own constructor to create them (without typos etc…) and check whether a given value (message) is of a particular kind.</p><p>The following example should given you a good idea of how to use daggy if you’ve never used it before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f208cf09ddb2171ba6fb9632fd9799fb/href">https://medium.com/media/f208cf09ddb2171ba6fb9632fd9799fb/href</a></iframe><h3>A couple of loose ends &amp; conclusion</h3><p>CSP-unrelated, we’re using <a href="https://www.npmjs.com/package/meow">meow</a> for CLI arg parsing and then calling the following main function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c17c4a86c19a8e274dbfc8edd5ad9aa5/href">https://medium.com/media/c17c4a86c19a8e274dbfc8edd5ad9aa5/href</a></iframe><p>Notice how we’re calling our initial go-routines (a.k.a processes, a.k.a generator functions — wow such names).</p><p>More importantly, notice that you cannot just yield in any old function — it must be a generator function. What’s more, you cannot just csp.take / put in any old generator function — it must be a generator function kicked off with csp.go . Hence the use of the helper function put above — which allows us to send the first few messages to kick off the whole thing (setting the project name and making our first HTTP request for the list of contributors).</p><h4>Yes it takes a while</h4><p>Note: if you’re actually going to try running this — it does take a while. The <a href="https://github.com/justin-calleja/github-cf/blob/master/cli.js">default</a> owner/repo combo is ubulonton/js-csp and <a href="https://github.com/justin-calleja/github-cf/blob/master/out.json">the output</a> took about 1min 35sec to complete (I used <a href="https://linux.die.net/man/1/time">time</a> for this).</p><p>If you see the <a href="https://github.com/justin-calleja/github-cf/blob/master/src/index.js#L115-L142">reducer’s code on Github</a> , you’ll notice I’m not mutating the state and opting to copy over values instead. You might think that mutation would speed things up — but I tried doing so and there was only around a 1sec difference between the two.</p><p>In hind sight — the real issue is that not much is happening concurrently here folks lol… hey you gotta start somewhere right? At least you now know the basics of js-csp — perhaps you could write a concurrent version of this as an exercise? Or perhaps I’ll do just that next time. (liking the post doesn’t hurt :P)</p><p><strong>Edit: </strong><a href="https://medium.com/@calleja.justin/getting-started-with-js-csp-part-2-35e7e650a57f"><strong>Read part 2 here.</strong></a></p><h4>Got some js-csp examples in mind?</h4><p>As an FYI, the people behind <a href="https://github.com/ubolonton/js-csp">js-csp</a> are currently looking to <a href="https://github.com/ubolonton/js-csp/issues/118#issuecomment-302222792">document some pragmatic use of the CSP model in JS</a>, particularly:</p><blockquote>how channels can help synchronize state in an interactive web app.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=232548ef94ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming in Javascript — an example]]></title>
            <link>https://medium.com/@calleja.justin/functional-programming-in-javascript-an-example-47116c2c3d00?source=rss-4f0e08b23b2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/47116c2c3d00</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ramda]]></category>
            <category><![CDATA[fantasy-land]]></category>
            <category><![CDATA[ramda-fantasy]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Justin Calleja]]></dc:creator>
            <pubDate>Wed, 01 Feb 2017 10:22:58 GMT</pubDate>
            <atom:updated>2017-02-01T10:22:58.577Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m just getting started with “Functional Programming” in Javascript and thought I’d share some code and explain some things along the way.</p><p>If you’ve been writing declarative code for a while, this post may not be for you. A bit of background. My inspiration for this style of coding came from <a href="https://egghead.io/lessons/javascript-linear-data-flow-with-container-style-types-box?course=professor-frisby-introduces-composable-functional-javascript">this video series</a> by <a href="https://medium.com/u/a3129fead82b">Brian Lonsdorf</a>. So if you’ve just watched it, this might be a nice “follow up”.</p><p>So… what shall we be building? The idea is to stretch our FP muscles a bit and write a simple CLI app which will find the closest parent package.json file, read its dependencies, find each dependency’s package.json in node_modules, and finally print out a report of sorts — lets print each dependency’s name, its <a href="http://semver.org/">semver</a> range, and the actual version installed in node_modules.</p><p>The repo with the final state of the code example is here: <a href="https://github.com/justin-calleja/depv">https://github.com/justin-calleja/depv</a></p><p>Also, it’s been published to npm so you can install it globally with:</p><pre>$ npm i -g @justinc/depv</pre><p>… and run it with $ depv</p><h4>Setting up</h4><p>Let’s start by installing all required modules:</p><pre>$ npm init --yes<br>$ npm i --save ramda ramda-fantasy read-pkg read-pgk-up columnify</pre><p>A word or two on what I think you should know about <a href="http://ramdajs.com/">Ramda</a> and <a href="https://github.com/ramda/ramda-fantasy">ramda-fantasy</a> — the main FP modules in this project.</p><p>You might be familiar with using utility libraries like <a href="http://underscorejs.org/">Underscore.js</a>, or <a href="https://lodash.com/">Lodash</a>. <a href="http://ramdajs.com/">Ramda</a> is similar; but keep the following in mind when using it:</p><ol><li>All functions are <a href="https://egghead.io/lessons/javascript-currying-with-examples">curried</a>.</li><li>Since functions like map, reduce etc… are curried, the value on what to act is passed as <strong>the last parameter.</strong></li></ol><p><a href="https://github.com/ramda/ramda-fantasy">ramda-fantasy</a> defines some <a href="https://github.com/fantasyland/fantasy-land">Fantasy Land</a> compatible types, most relevant of which for this article is the <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Future.md">Future</a> type. From what I understand, Fantasy Land, for e.g., specifies what it means for a Javascript object to be a <a href="https://github.com/fantasyland/fantasy-land#functor">Functor</a>, or an <a href="https://github.com/fantasyland/fantasy-land#applicative">Applicative</a>, or a <a href="https://github.com/fantasyland/fantasy-land#monad">Monad</a>, or for it to be a <a href="https://github.com/fantasyland/fantasy-land#chainrec">ChainRec</a> — and ramda-fantasy’s <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Future.md">Future</a> type implements all these “interfaces” / “specs”. You don’t need to fully understand these specs / interfaces — there’s enough documentation on how to use a <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Future.md">Future</a> so we can start using it and develop some intuition re the spec definitions.</p><p>Other than these modules, we’re using <a href="https://github.com/sindresorhus/read-pkg-up">read-pkg-up</a>, <a href="https://github.com/sindresorhus/read-pkg">read-pkg</a>, and <a href="https://github.com/timoxley/columnify">columnify</a>. You can read their docs to get an idea of what they do.</p><p>One note re read-pkg-up, the Promise it returns resolves to an Object with keys pkg for the parsed contents of apackage.json file (an Object), and path for the absolute path to the parsed package.json (a String).</p><h4>The result of read-pgk-up as a (cached) Future</h4><pre>const readPkgUpAsPromised = require(&#39;read-pkg-up&#39;);</pre><pre>// readPkgUpResultF :: Future Error Object<br>// The resolved Object is of the form: { pkg, path }<br>const readPkgUpResultF = Future.cache(<br>  Future((rej, res) =&gt; {<br>    console.log(&#39;about to call readPkgUpAsPromised&#39;);<br>    readPkgUpAsPromised().then(res).catch(rej)<br>  })<br>);</pre><p>I’m requiring read-pkg-up as readPkgUpAsPromised to emphasise that it has a Promise based API.</p><p>readPkgUpResultF is a Future. What’s more, it’s been <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Future.md#futurecache">cached</a>. I’m pretty sure I only want to read the base package.json once when running this app, so I’m caching the operation. Let’s have a look at what that means. Try adding:</p><pre>const { Future } = require(&#39;ramda-fantasy&#39;);</pre><pre>// pkgJSONF :: Future Error Object<br>const pkgJSONF = readPkgUpResultF.map(({ pkg }) =&gt; pkg);<br>// pathF :: Future Error String<br>const pathF = readPkgUpResultF.map(({ path }) =&gt; path);</pre><pre>// whateverF :: Future Error String<br>const whateverF = pkgJSONF.chain(pkgJSON =&gt; {<br>  console.log(`pkgJSON is:\n${JSON.stringify(pkgJSON, null, 2)}`);<br>  return pathF.map(path =&gt; {<br>    console.log(`path is:\n${path}`);<br>    return &#39;whatever&#39;;<br>  });<br>});</pre><pre>whateverF.fork(console.error, console.log);</pre><p>Running this code ($ node whatever.js) gives:</p><pre>about to call readPkgUpAsPromised<br>pkgJSON is:<br>{<br>  &quot;name&quot;: &quot;depv&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;<br>  },<br>  &quot;keywords&quot;: [],<br>  &quot;author&quot;: &quot;&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;columnify&quot;: &quot;^1.5.4&quot;,<br>    &quot;ramda&quot;: &quot;^0.23.0&quot;,<br>    &quot;ramda-fantasy&quot;: &quot;^0.7.0&quot;,<br>    &quot;read-pkg&quot;: &quot;^2.0.0&quot;,<br>    &quot;read-pkg-up&quot;: &quot;^2.0.0&quot;<br>  },<br>  &quot;readme&quot;: &quot;ERROR: No README data found!&quot;,<br>  &quot;_id&quot;: &quot;depv@1.0.0&quot;<br>}<br>path is:<br>/Users/justin/functional-tmp/depv/package.json<br>whatever</pre><p>As you can see &quot;about to call readPkgUpAsPromised “ is only logged <strong>once</strong>. If you remove the wrapping Future.cache in readPkgUpResultF‘s definition, it’ll log out twice.</p><p>So what’s whateverF? Basically, I just wanted one Future (whateverF) which would “depend on” — and therefore “force the execution of” the two Futures pkgJSONF and pathF (which in turn “force the execution of” readPkgUpResultF). So readPkgUpResultF ends up having to be “resolved” to a value twice, once to extract the package JSON object, and once to get the path. But since readPkgUpResultF is a Future I’ve created with Future.cache — the wrapped Future is only executed once and the value it resolves to (or rejects to) on first execution is returned by the wrapping Future on any subsequent resolution requests.</p><p>You might have noticed the use of <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Future.md#futuremap">map</a> and <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Future.md#futurechain">chain</a> in whateverF‘s definition. It’s important to understand what they’re doing (we’ll be using them a lot).</p><p>The idea is very simple. Currently, we’re working with a data-structure (or type) called a Future. Only <strong>definitions</strong> have taken place so far — things akin to:</p><pre>let a = 2;</pre><p>… that’s it — no side-effects have been triggered so far (no files have been read and no console logging either).</p><p>Everything changes once we call a Future‘s <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Future.md#futurefork">fork</a> method, passing in the error handler first, and the success handler second.</p><p>fork is our trigger — it actually runs <em>the code</em> we’re wrapping in a Future. But what is this <em>code</em>? We’ll we’re still building it up until the moment we call fork.</p><p>So let’s take pkgJSONF for example. What’s the code which will run when we trigger it with fork ?</p><pre>const pkgJSONF = readPkgUpResultF.map(({ pkg }) =&gt; pkg);</pre><p>pkgJSONF is a Future which we construct by mapping over another Future, readPkgUpResultF:</p><pre>const readPkgUpResultF = Future.cache(<br>  Future((rej, res) =&gt; readPkgUpAsPromised().then(res).catch(rej))<br>);</pre><p>So, we can intuitively see that forking pkgJSONF will somehow run:</p><pre>(rej, res) =&gt; readPkgUpAsPromised().then(res).catch(rej)</pre><pre>// followed by:</pre><pre>({ pkg }) =&gt; pkg)</pre><p>map somehow joins the two together. And so does chain. Both are used to create a Future from a given Future by appending (or composing) more code to the existing code in the given Future. The only difference is that map wraps the result of its given function back into a Future, while chain does not. chain expects its given function to return a Future. Both have their uses, and both methods work exactly the same with other monadic types like <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Either.md">Either</a>, <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Maybe.md">Maybe</a>, etc…</p><p>Let’s look at whateverF again:</p><pre>// whateverF :: Future Error String<br>const whateverF = pkgJSONF.chain(pkgJSON =&gt; {<br>  return pathF.map(path =&gt; {<br>    return &#39;whatever&#39;;<br>  });<br>});</pre><p>whateverF is a Future Error String, i.e. it’s a Future which resolves to an Error or a String. Had we used map instead of chain in the “pkgJSONF.chain” call — what do you think whateverF ‘s “type” would be?</p><p>It would be a Future Error (Future Error String). Why? Because calling map on a Future instance with function f will create a new Future instance whose “wrapped code” (to run on fork) will be whatever the previous Future’s code was “+ the code in f” BUT, the “+ the code in f&quot; part only runs with the previous Future’s <strong>resolved</strong> value. If the previous Future’s wrapped code ends up Erroring out, f never runs. (there are other Future methods to create new Futures based on existing ones but which extend the Error case instead).</p><p>To recap, you can image that map kind of “extracts” the resolved value of a Future, passes it to its given function f and then re-wraps f&#39;s result in a Future. This is not what it does when you call map (remember: everything is lazy, nothing runs) — but it might help making sense of things. What map actually does is create a new value.</p><p>So you should be able to see now that if we want to access the future values resolved by both pkgJSONF and pathF, we must chain and then map, otherwise we’ll get nested Futures. We’ll see another way of doing this via “lifting” later on.</p><h4>Moving on</h4><p>Now that we have a better understanding of what a Future is and how map and chain can be used to create new ones, let’s continue our running example.</p><p>So far we have future access to a parsed package.json and its path via pkgJSONF and pathF. My plan of attack is going to be to aim to get a dict (Javascript Object) of “dependency name (key) to semver range (value)” and another one of “dependency name (key) to actual version number (value)” (depSemverRangeDictF and depVersionDictF respectively). Once I have these, it should be fairly easy to create a new Object to feed to columnify as data — which in turn will give us a nicely formatted string to print to the user.</p><p>depSemverRangeDictF is easy:</p><pre>// depSemverRangeDictF :: Fututre Error Object<br>const depSemverRangeDictF = pkgJSONF.map(pkgJSON =&gt; pkgJSON.dependencies);</pre><p>Now to define depVersionDictF , I’m going to need an array of parsed package.json files, one for each dependency found in pkgJSON.dependencies — i.e. it seems necessary to access depSemverRangeDictF&#39;s keys (the dependency names):</p><pre>// depNamesF :: Future Error [String]<br>const depNamesF = depSemverRangeDictF.map(Object.keys);</pre><p>This is pretty straightforward at this point — we’re “unwrapping” the dict and passing it to Object.keys. Nothing new. So since our cognitive load’s a bit low right now, let’s look at an equivalent way of doing this:</p><pre>var { map } = require(&#39;ramda&#39;);<br>const depNamesF = map(Object.keys, depSemverRangeDictF);</pre><p>How come Ramda’s map works on Futures? From the <a href="http://ramdajs.com/docs/#map">docs</a>:</p><blockquote>Takes a function and a <a href="https://github.com/fantasyland/fantasy-land#functor">functor</a>, applies the function to each of the functor’s values, and returns a functor of the same shape.</blockquote><blockquote>…</blockquote><blockquote>Dispatches to the map method of the second argument, if present.</blockquote><p>i.e. Ramda’s map works on <a href="https://github.com/fantasyland/fantasy-land#functor">functors</a>. The Future monad (as well as JS’s arrays) are functors as they have a map method and obey the following:</p><ol><li>u.map(a =&gt; a) is equivalent to u (identity)</li><li>u.map(x =&gt; f(g(x))) is equivalent to u.map(g).map(f) (composition)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HiEozqEKPrzZGTrMuJcmuQ.png" /></figure><p>Moving on… now that we have our dependency names, we need a way to turn them into absolute paths to each dependency’s package.json file so we can then read them with theread-pkg module:</p><pre>const { join } = require(&#39;path&#39;);<br>const { lift } = require(&#39;ramda&#39;);</pre><pre>// joinPaths :: String -&gt; [String] -&gt; [String]<br>const joinPaths = (basePath, names) =&gt; names.map(name =&gt; join(basePath, name));</pre><pre>// mjoinPaths :: M String -&gt; M [String] -&gt; M [String]<br>const mjoinPaths = lift(joinPaths);</pre><p>What’s going on here? Well, joinPaths is simple enough — it’s a normal function which given a string and an array of strings returns an array of strings. But normal functions don’t know how to work with functors (unwrapping and re-wrapping them).</p><p>That’s what <a href="http://ramdajs.com/docs/#lift">lift</a> is being use for. The lifted function mjoinPaths can now work with our Future monads.</p><p>You might want to have a look at <a href="https://egghead.io/lessons/angular-1-x-applicative-functors-for-multiple-arguments">this video</a> for a better understanding of lift. Note that ramda-fantasy&#39;s Future, being a Monad, implements the <a href="https://github.com/fantasyland/fantasy-land#apply">Apply</a> spec. lift can be defined in terms of ap — the method the Apply spec requires on its implementors.</p><p>All this means that we now have a way to get the absolute path to each of our dependencies in our node_modules:</p><pre>const { resolve } = require(&#39;path&#39;);</pre><pre>// depPathsF :: Future Error [String]<br>const depPathsF = mjoinPaths(<br>  pathF.map(path =&gt; resolve(path, &#39;../node_modules&#39;)),<br>  depNamesF<br>);</pre><p>And now it’s just a matter of <em>somehow</em> passing each depPath in depPathsF through the wrapped read-pkg module:</p><pre>const { traverse } = require(&#39;ramda&#39;);<br>const readPkgAsPromised = require(&#39;read-pkg&#39;);</pre><pre>// readPkg :: String -&gt; Future Error Object<br>const readPkg = path =&gt; <br>    Future((rej, res) =&gt;<br>        readPkgAsPromised(path).then(res).catch(rej));</pre><pre>// depsPkgJSONF :: Future Error [Object]<br>// The package.json of each dependency as an object<br>const depsPkgJSONF = depPathsF.chain(traverse(Future.of, readPkg));</pre><p>This gives us the opportunity to introduce a new pattern. What’s this traverse business?</p><p>What if we tried this instead:</p><pre>// depsPkgJSONF :: Future Error [Future Error Object]<br>const depsPkgJSONF = depPathsF.map(depPaths =&gt; map(readPkg, depPaths));</pre><pre>const loggers = [console.error, console.log];<br>depsPkgJSONF.fork(...loggers);</pre><pre>// outputs:<br>[ Future { _fork: [Function] },<br>  Future { _fork: [Function] },<br>  Future { _fork: [Function] },<br>  Future { _fork: [Function] },<br>  Future { _fork: [Function] } ]</pre><p>As you can see, we get back a Future (since a functor’smap will wrap the value back in a Future). But this Future resolves to an array of Futures, instead of the parsed package.json files.</p><p>What if we try this instead:</p><pre>const { sequence } = require(&#39;ramda&#39;);</pre><pre>const depsPkgJSONF = depPathsF.chain(depPaths =&gt; {<br>  return sequence(Future.of, map(readPkg, depPaths));<br>});</pre><pre>depsPkgJSONF.fork(...loggers);</pre><p>Notice how we’re re-using the trick of starting with a chain when the chain&#39;s callback returns a wrapped value (map would re-wrap twice as we discussed before).</p><p>If you run this, it’ll work just like when we used traverse since the two are equivalent:</p><pre>const depsPkgJSONF = depPathsF.chain(traverse(Future.of, readPkg));</pre><p>traverse:</p><blockquote>Maps an <a href="https://github.com/fantasyland/fantasy-land#applicative">Applicative</a>-returning function over a <a href="https://github.com/fantasyland/fantasy-land#traversable">Traversable</a>, then uses <a href="http://ramdajs.com/docs/#sequence">sequence</a> to transform the resulting Traversable of Applicative into an Applicative of Traversable.</blockquote><p>i.e. — my interpretation:</p><ul><li>traverse maps readPkg (an Applicative-returning functions since it returns a Future Monad — and any Monad is also an Applicative) over a Traversable (depPaths).</li><li>The Traversable in our case a JS Array… and honestly, I’m not sure why it works over an Array since it’s not a <a href="https://github.com/fantasyland/fantasy-land#traversable">Traversable</a> as per the Fantasy Land spec. Arrays have no traverse method. It works anyway so I’m assuming Ramda treats Arrays as a special case to make it work as if it were a type implementing Traversable (Arrays <em>do</em> implement the <a href="https://github.com/fantasyland/fantasy-land#functor">Functor</a> and <a href="https://github.com/fantasyland/fantasy-land#foldable">Foldable</a> specifications — pre-requisites for implementations of Traversables).</li><li>The result of the map operation is then fed to <a href="http://ramdajs.com/docs/#sequence"><em>sequence</em></a><em> — </em>which also uses the first argument we pass in <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Future.md#futureof">Future.of</a> to do its work.</li></ul><p><a href="http://ramdajs.com/docs/#sequence">sequence</a>:</p><blockquote>Transforms a <a href="https://github.com/fantasyland/fantasy-land#traversable">Traversable</a> of <a href="https://github.com/fantasyland/fantasy-land#applicative">Applicative</a> into an Applicative of Traversable.</blockquote><blockquote>e.g.</blockquote><blockquote>R.sequence(Maybe.of, [Just(1), Just(2), Just(3)]); //=&gt; Just([1, 2, 3])</blockquote><p>The example is given using the <a href="https://github.com/ramda/ramda-fantasy/blob/master/docs/Maybe.md">Maybe</a> Monad, but it might as well have been a Future:</p><pre>// x :: [Future Error Object]<br>// let x = map(readPkg, depPaths)</pre><pre>R.sequence(Future.of, x)</pre><p>So basically, we’re using sequence to change an array of Futures i.e. [Future Error Object] — into a Future Error [Object] — again this is just data manipulation so nothing runs — we’re just modifying data structures.</p><p>For more info on this, you can watch<a href="https://egghead.io/lessons/javascript-leapfrogging-types-with-traversable"> this video</a> in <a href="https://medium.com/u/a3129fead82b">Brian Lonsdorf</a>’s excellent video series.</p><h4>And finally</h4><p>Now that we have our depsPkgJSONF , it should be easy to change it into the “dependency name (key) to actual version (value)” Object we originally wanted:</p><pre>const depVersionDictF = depsPkgJSONF.map(depsPkgJSON =&gt; {<br>  return depsPkgJSON.reduce((acc, val) =&gt; {<br>    acc[val.name] = val.version;<br>    return acc;<br>  }, {});<br>});</pre><p>And finally, we can use our two dictionaries (JS Objects) to shape the input for columnify:</p><pre>const depsColumnifyDataF = lift((depNames, depSemverRangeDict, depVersionDict) =&gt; {<br>  return depNames.map(name =&gt; {<br>    return {<br>      dependency: name,<br>      &#39;semver-range&#39;: depSemverRangeDict[name],<br>      &#39;installed-version&#39;: depVersionDict[name]<br>    }<br>  });<br>})(depNamesF, depSemverRangeDictF, depVersionDictF);</pre><pre>depsColumnifyDataF.map(columnify).fork(...loggers);</pre><p>And we’re done!</p><p>Running the program gives us something like:</p><pre>DEPENDENCY    SEMVER-RANGE INSTALLED-VERSION<br>columnify     ^1.5.4       1.5.4<br>ramda         ^0.23.0      0.23.0<br>ramda-fantasy ^0.7.0       0.7.0<br>read-pkg      ^2.0.0       2.0.0<br>read-pkg-up   ^2.0.0       2.0.0</pre><h4>Final notes</h4><p>The final example looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7c3b7818d84072359df21a405709091/href">https://medium.com/media/b7c3b7818d84072359df21a405709091/href</a></iframe><p>Notice how re-usable our code is. The depv module’s main script is src/index.js — from which we’re exporting our data-structures (Futures). We’re using one in cli.js and nothing’s stopping us from requiring this published module and re-using it in another project:</p><pre>$ mkdir demo &amp;&amp; cd demo<br>$ npm init --yes<br>$ npm i --save @justinc/depv<br>$ vim index.js<br></pre><pre>var { depSemverRangeDictF } = require(&#39;<a href="http://twitter.com/justinc/depv">@justinc/depv</a>&#39;);</pre><pre>depSemverRangeDictF.fork(console.error, console.log);<br></pre><pre>$ node index.js<br>{ &#39;<a href="http://twitter.com/justinc/depv">@justinc/depv</a>&#39;: &#39;^1.0.2&#39; }</pre><p>I hope you enjoyed this post and are interested in further exploring this style of programming.</p><p>If you know of any “recommended reading” re this style of programming in JS, please share! I’m @justin_calleja on Twitter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47116c2c3d00" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>