<?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 Slobodan Blazeski on Medium]]></title>
        <description><![CDATA[Stories by Slobodan Blazeski on Medium]]></description>
        <link>https://medium.com/@bobiblazeski?source=rss-1f63bedf8567------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*9fDIxEPsjB5JWDx7.jpeg</url>
            <title>Stories by Slobodan Blazeski on Medium</title>
            <link>https://medium.com/@bobiblazeski?source=rss-1f63bedf8567------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 00:06:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bobiblazeski/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[Scope and Efficiency: Why Development Fails Where Productivity Succeeds]]></title>
            <link>https://medium.com/@bobiblazeski/scope-and-efficiency-why-development-fails-where-productivity-succeeds-a810f57c0edf?source=rss-1f63bedf8567------2</link>
            <guid isPermaLink="false">https://medium.com/p/a810f57c0edf</guid>
            <dc:creator><![CDATA[Slobodan Blazeski]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 15:00:07 GMT</pubDate>
            <atom:updated>2026-01-14T15:00:07.825Z</atom:updated>
            <content:encoded><![CDATA[<p>Most debates about development obsess over productivity, technology, and institutions. They ask why firms are inefficient, why capital is misallocated, or why governance is weak. This focus misses a more basic constraint. Many economies fail not because they use resources badly, but because too little of their potential economy exists in the first place.</p><p>This post lays out a simple but unforgiving framework. Economic development unfolds along two distinct dimensions: <strong>scope</strong> and <strong>efficiency</strong>. Confusing the two leads to policy failure, political backlash, and repeated cycles of deindustrialization.</p><h3>1. Scope versus Efficiency</h3><p><strong>Scope</strong> measures how much of a country’s productive potential is activated. It is about breadth rather than quality. Scope includes how many sectors operate, how much labor is absorbed into monetized production, how geographically spread economic activity is, and whether firms are embedded in dense supplier and learning networks. A high-scope economy employs most of its people, links regions through production, and sustains many imperfect but functioning industries. A low-scope economy is narrow. Activity is concentrated in enclaves such as minerals, cash crops, or protected urban services, while large shares of land and labor sit idle or informal.</p><p><strong>Efficiency</strong> measures how well resources are used within whatever scope already exists. High efficiency means high utilization, disciplined management, low waste, and exposure to competition. Low efficiency means idle plants, soft budget constraints, poor maintenance, and weak incentives.</p><p>The crucial asymmetry is that efficiency is conditional on scope. You can only be efficient in sectors that exist. You cannot raise productivity in activities that never formed.</p><h3>2. Four Economic States</h3><p>Combining scope and efficiency yields four stylized economic states.</p><ul><li><strong>Low Scope / Low Efficiency (LS/LE)</strong> describes collapsed or failing economies. Few sectors operate, capacity utilization is low, and much of the population is outside productive employment.</li><li><strong>Low Scope / High Efficiency (LS/HE)</strong> describes enclave economies. Production is narrow but well run: minerals, monocrops, offshore manufacturing, or elite services. These sectors look productive in isolation but generate few linkages.</li><li><strong>High Scope / Low Efficiency (HS/LE)</strong> describes broad but messy economies. Many sectors exist, labor is absorbed at scale, firms are small and inefficient, and learning dominates productivity. Early industrializers live here.</li><li><strong>High Scope / High Efficiency (HS/HE)</strong> describes developed economies. Production is diversified, competitive, and technologically advanced.</li></ul><p>These are not stages on a smooth continuum. Each quadrant is a locally stable political–economic equilibrium.</p><h3>3. The Transition Matrix</h3><p>The heart of the model is not the quadrants but the <strong>transition matrix</strong>. Movements between states are asymmetric because each quadrant is defended by a coalition that benefits from its structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*3DLkSemtenIlSCZfsRnrGg.png" /></figure><p>The key instability lies in the middle. Economies cannot remain at moderate scope and moderate efficiency. Under fiscal stress, external competition, or political conflict, adjustment occurs. When adjustment happens, <strong>scope is sacrificed before efficiency</strong>. Inefficiency is visible and politically embarrassing. Scope loss is slow, spatially dispersed, and easier to justify.</p><p>This explains why liberalization and crisis so often produce deindustrialization rather than upgrading.</p><h3>4. Why Enclaves Do Not Scale</h3><p>The most tempting but most dangerous state is <strong>LS/HE</strong>. Enclave sectors generate rents, foreign exchange, and impressive productivity statistics. They also generate coalitions that actively block scope expansion.</p><p>Moving from LS/HE to HS/LE requires tolerating inefficiency: protected firms, labor‑intensive production, learning by doing, and local competitors. Enclave elites oppose this rationally. Scope expansion dilutes rents, threatens control, and creates political rivals.</p><p>This is why diagonal jumps from enclave efficiency to broad efficiency do not occur. The institutional and human capital gap cannot be bridged by importing machinery or management alone.</p><h3>5. Coalitions and Political Economy</h3><p>Each quadrant corresponds to a dominant coalition.</p><p>Low-scope states are defended by importers, capital elites, and security services. Enclave economies are defended by exporters, multinationals, and technocrats. High-scope, low-efficiency economies are sustained by peasants, small industrialists, and regional power brokers. High-scope, high-efficiency economies are defended by diversified capital, skilled labor, and professional bureaucracies.</p><p>The decisive rule is simple: <strong>development is possible only when the ruling coalition does not block scope expansion</strong>. Institutions, property rights, and markets matter, but only after this condition is satisfied.</p><h3>6. The U-Shaped Development Path</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tno3Rx4FUU1K2bjuV94Ww.jpeg" /></figure><p>Putting these pieces together yields a single viable development path.</p><p>First, enclave economies break. External shocks, commodity collapses, sanctions, or political crises destroy coordination and investment, pushing LS/HE economies into LS/LE.</p><p>Second, scope is rebuilt. Economies expand through labor‑intensive, inefficient, and often protected activities. Productivity is low by design. What rises instead is absorptive capacity, organizational density, and general skills. This is the HS/LE phase.</p><p>Third, efficiency is imposed. Once scope is broad and coalitions include producers and labor, competition, export pressure, and selective reform raise productivity, yielding HS/HE.</p><p>Attempts to skip the middle phase fail because efficiency mechanisms require scope to operate.</p><h3>7. Technology, FDI, and Premature Efficiency</h3><p>Low-tech production expands scope. High-tech production raises efficiency. Confusing the two is fatal.</p><p>Foreign direct investment accelerates development only in high-scope economies, where it deepens linkages and disciplines firms. In low-scope economies it substitutes for local learning and entrenches enclaves. Capital-intensive technology raises measured productivity while shrinking the ecosystem that could sustain it.</p><h3>8. Stylized Transitions and Historical Cases</h3><p>The framework is abstract, but it maps cleanly onto real development trajectories. The value of the model is not prediction but classification: it explains why certain transitions repeatedly occur and others almost never do.</p><p><strong>Sub-Saharan Africa (Enclave → Collapse)</strong><br>Most African economies entered independence in an LS/HE configuration. Colonial rule created efficient but extremely narrow export enclaves in minerals and cash crops, with minimal domestic linkages. Post-independence big-push strategies attempted diagonal jumps by importing turnkey factories and heavy industry. These projects raised neither scope nor durable efficiency. When external financing dried up in the late 1970s and early 1980s, the enclaves fractured. Structural adjustment then formalized the collapse by stripping even the limited industrial scope that had emerged, returning many economies to LS/LE monocrop equilibria.</p><p><strong>Russia (Broad Scope → Enclave Efficiency)</strong><br>The Soviet economy was firmly HS/LE: extremely broad industrial scope combined with low efficiency. Liberalization in the 1990s did not move Russia upward to HS/HE. Instead, competitive pressure and fiscal collapse led to rapid scope contraction. Consumer manufacturing, light industry, and regional production networks disappeared, while minerals, energy, defense, and a handful of capital-intensive sectors survived as LS/HE enclaves. Efficiency was preserved where rents allowed it; scope was sacrificed elsewhere.</p><p><strong>Australia (Deindustrialization via Enclave Pressure)</strong><br>Australia illustrates how even advanced economies can move down and right. A commodity boom combined with a small domestic market made manufacturing politically expendable. Under competitive pressure, inefficient tradable manufacturing was sacrificed first, while mining, housing, education, and other enclave-like sectors expanded. The economy shifted from HS/ME toward LS/HE specialization, not because manufacturing was unproductive globally, but because enclave sectors dominated the coalition.</p><p><strong>China (Scope First, Efficiency Later)</strong><br>Mao-era China constructed enormous scope at very low efficiency through communes and state industry. The system was wasteful but learning-rich. Millions of workers acquired technical, organizational, and managerial skills. Deng-era reforms did not create scope from scratch; they raised efficiency within an already broad production structure via Township and Village Enterprises, export discipline, and selective openness to FDI. The HS/LE phase made the HS/HE transition feasible.</p><p><strong>United Kingdom (Efficient Sectors Crowding Out Scope)</strong><br>Britain’s post-1970 trajectory mirrors the logic of scope sacrifice. Finance, North Sea oil, property, and elite services were globally competitive and politically powerful. Manufacturing was fragmented, regionally embedded, and relatively inefficient. Liberalization preserved efficiency where it already existed and allowed scope to shrink elsewhere. The result was not universal upgrading but a shift toward LS/HE specialization within a rich economy.</p><p><strong>Zimbabwe (Enclave Destruction without Scope Replacement)</strong><br>Zimbabwe entered independence with a narrow but highly efficient commercial farming enclave. Expropriation destroyed that enclave, pushing the economy from LS/HE to LS/LE. Crucially, no broad scope-building coalition replaced it. The result was collapse rather than transition.</p><p><strong>Nigeria (Unstable Middle via Rents)</strong><br>Nigeria is unusual in that oil rents were large enough to partially expand scope, but not large enough to sustain efficiency. Informal and semi-formal manufacturing clusters emerged outside the patronage system, while rents simultaneously prevented full scope expansion and disciplined competition. The economy oscillates near the unstable middle, with repeated pressures to collapse back into enclave equilibrium.</p><h3>9. Conclusion</h3><p>Backsliding is easy because shrinking scope is always politically simpler than tolerating inefficiency. Mineral rents bias economies toward enclave equilibria. Countries without rents are forced, sometimes brutally, onto the high-scope path.</p><p>You can import machines. You cannot import a population-wide production structure. That has to be built, inefficiently, before it can be refined.</p><p><strong>No economy reaches high scope and high efficiency without passing through high scope and low efficiency first.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a810f57c0edf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building end to end JavaScript application]]></title>
            <link>https://medium.com/@bobiblazeski/building-end-to-end-javascript-application-7083ac6000c9?source=rss-1f63bedf8567------2</link>
            <guid isPermaLink="false">https://medium.com/p/7083ac6000c9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rethinkdb]]></category>
            <dc:creator><![CDATA[Slobodan Blazeski]]></dc:creator>
            <pubDate>Mon, 07 Mar 2016 13:14:58 GMT</pubDate>
            <atom:updated>2016-03-07T13:17:21.691Z</atom:updated>
            <content:encoded><![CDATA[<p>Late summer 2015 I left my job as head of IT and went back to building applications full time. I was using Node &amp; React on a smaller projects but I wanted to see how it will work on large application and get the idea how end to end JavaScript application feels. Since my designer skills are limited at best I have a luck working with Sebastian, whose domain expertise was invaluable.</p><h4>Choosing the stack</h4><p>As a developer I got the full freedom of choosing the stack we would use in the application, and all the responsibility that goes with it if something goes wrong. I’ve chosen combination of React for the view layer, Webpack as bundler, Socket.Io for real-time communication,Ramda as utility library,Koa as web framework and RethinkDB as database. Fallowing the rule that in every project there should be no more than one technology that’s pushing the edge I decided for it to be RethinkDB. The rest of the stack were tried and proved technologies that I already used in previous projects beside Koa. Since I have great experience with TJ’s libraries I was sure that it would perform great.</p><h4>Orchestrating the stack</h4><p>Though all the technologies felt great making them play well turned quite interesting endeavor. At first I planned to use either Redux or Cerebral, but both were very new, lacked resources to learn from and I had a feeling the Dan &amp; Christian are changing them every week. Having already chosen one cutting edge technology I decided to write my own dispatching.</p><p>My approach was having unidirectional data flow, all the state stored in single immutable store and passing all the data downstream. I avoided all technologies that used implicit data passing. I wanted one root components and data being explicitly sent. The solution I came up with is having all the available actions stored as keys into one object. Below is a sample action function.</p><pre>function (data,dispatch,model,transfer){ <br>   return model.setIn([‘filter’,’distance’], data);<br>}</pre><p>The parameters are as fallowing: data being data sent by the control, the dispatcher itself, the full model of the application and the transfer object which is used for communication between client and the server. Every action returns the new immutable store that is being sent to root component.</p><p>The passing became quite wordy but one found one neat trick to pick the data needed using the propTypes and pass them downstream.</p><pre>&lt;Hero {…(U.props(Hero.propTypes, this.props))} /&gt;</pre><h4>Server side rendering</h4><p>In order to improve user experience I wanted server side rendering from the very beginning. Since the application was structured as root component that only depended on the data being sent, the server side rendering was nearly trivial. I used React as server site renderer and it served me quite well. Below is the first and simplest version of the renderer.</p><pre>Renderer.render = function(model){ <br>  var startState= JSON.stringify(model.asObject()); <br>  var body = React.renderToString(App({model: model})); <br>   var html = React.renderToStaticMarkup(Layout({<br>       body : body,   <br>       startState : startState <br>   })); <br>   return ‘&lt;!DOCTYPE html&gt;’+html;<br>}</pre><p>The same renderer approach was used for rendering emails HTML. React server side rendering obviates need for separate templating system.</p><h4>Real-time communication</h4><p>I started very hyped on the RethinkDB, it has ability to subscribe to feed streams that simplified development and enabled my code to be disentangled. I could simple listen to feed and take the appropriate actions, it felt to good to be true. Unfortunately I started to have problem with stale data, RethinkDB has a joins which is great, but they are not real-time joins which completely negates the advantages. In the end I had to swallow my pride and removed all the RethinkDB feeds from the application and relied on Socket.io server to coordinate actions.</p><p>I still believe that RethinkDB is a great database but without real-time joins its use is quite limited.</p><h4>Hosting</h4><p>I did some research on various options on the AWS platform, but got quickly overwhelmed and since our stack was already preordained I have the feeling that in order to use all the AWS goodies you need to plan your app from start. In the end we went for digital ocean, which offered cheap VMs with solid state drives and co-location. I was thinking about hosting our RethinkDB database at compose but digital ocean was way too cheap and having our database linked with ultra fast intranet meant a lot. We added Nginx to handle certificates and server as reverse proxy.</p><p>The only thing I miss at digital ocean is ability make backups more often. Also finding out that my designer is better at administering Linux boxes hurt a lot.</p><h4>Security</h4><p>The real headache happened before the pre-launch when we put our site and asked the white hat community for tips. We immediately got hammered with XSS attacks. JavaScript lack of type safety and my inexperience in securing applications hosted outside of secured intranets quickly showed. Luckily I planned for the boring conservative validation of the code on the both client and server side, so I patched the forms and the cookies. The largest problem was serializing the state of the application. To my own horror I found that rendering the result of JSON.stringify doesn’t give readable state on the client. I had to sanitize my model and put it into script tag as template/text.</p><h4>Testing</h4><p>Having combination of purely functional components and testing with mocha, chai &amp; React testing utilities made testing relatively easy and fast. The problem with our setup was that it wasn’t integrated with the commit process thus enabling to cheat by committing code that failed the tests. The second problem was more with JavaScript lack of types. In the beginning I love the dynamic typing since it enables me to experiment while the problem is ill defined, but later when I had idea what I want it becomes a burden. Refactoring dynamically typed code always gives me that nagging feeling that I overlooked something, even when all the tests are passing. It’s a very unsettling feeling that never goes away.</p><p>In the end I really enjoyed working on <a href="https://www.supto.com/">Supto</a>, it proved to me that end to end JavaScript application work great, and that ecosystem is learning and innovating on unprecedented pace. And that’s not a JavaScript fatigue, it’s a sweet pain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7083ac6000c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I use React for EVERYTHING]]></title>
            <link>https://medium.com/@bobiblazeski/why-i-use-react-for-everything-bb4808c16d62?source=rss-1f63bedf8567------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb4808c16d62</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Slobodan Blazeski]]></dc:creator>
            <pubDate>Sun, 30 Aug 2015 10:35:18 GMT</pubDate>
            <atom:updated>2015-08-30T10:35:18.343Z</atom:updated>
            <content:encoded><![CDATA[<p>React is becoming quite popular and with all that comes both deserved prizing and some hype. I’ve heard the question why am I using React for pretty much everything while chatting with fellow developers, at job interviews and lately my twitter feed is filled with articles promoting other frameworks. Since I’m starting to get bored repeating myself, here are my reasons why am I using React for everything:</p><h4>Small</h4><p>React is quite small and very easy to learn. You could pick up the basics very fast and dive right into making your applications. I like to build things not spend time reading tutorials and browsing documentation.</p><h4>Fast</h4><p>React is fast out of the box. Unburdening me to ignore speed is a huge win for being able to think about my application not why does it take 4 seconds to see that update.</p><h4>JSX</h4><p>At the start I was very skeptical about JSX, but then I remembered to<a href="http://thebuddhistblog.blogspot.com/2007/08/zen-story-cup-of-tea.html"> empty my cup</a> and start with a beginner’s mind. I found JSX very practical to both recreate pre-made themes and to communicate with web designers. I still like Jade, but JSX has its advantages and lately I prefer to use it.</p><h4>Battle tested</h4><p>I generally avoid using more then one new technology in my stack. Since I’m mostly working on real-time lately that place is reserved for RethinkDB. React being battle proven on many large production applications ensures me that I’ll minimize those weird bugs that appear in every new technology.</p><h4>Server side rendering</h4><p>React enables me to render my application on the server and send it on the client where it comes alive. This excludes the ugly flickering and enables the user to interact immediately with the application. Being perceived as slow is a killer to good user experience.</p><h4>Isomorphic JavaScript</h4><p>React powered by webpack makes very natural to share code between client and server. I have one templating system, one router, one validation logic, used at both the client and the server.</p><h4>Functional</h4><p>React encourages functional programming as default approach. When looking at my React components at my latest project I see only render methods and occasional handlers. I know that you could use functional approach with other frameworks but when its unidiomatic you’re just putting unnecessary burden trying to fit square pegs into round holes.</p><h4>Unidirectional data flow</h4><p>This is a huge win and probably the best idea from React. I know it was used elsewhere first but React made it popular in the web development world. I found the triad of Action, Store, View where Action updates Store, Store re-renders View, and view triggers actions the right way of communicating between different layers. There is a lot of development going on in this area, with <a href="https://github.com/rackt/redux">Redux </a>, <a href="https://github.com/christianalfoni">Cerebral</a> and <a href="http://cycle.js.org/">Cycle</a> in the JavaScript world, and <a href="http://elm-lang.org/">Elm</a> if you want to go really hardcore and learn a new language.</p><h4>Native</h4><p>Enables you to write native applications for iOS with Android on the way. Like <strong>Atwood’s Law </strong>clearly states: any application that <em>can</em> be written in JavaScript, <em>will</em> eventually be written in JavaScript.</p><h4>Libraries</h4><p>Popularity brings a lot of tools and components that you need in your application but will take huge time to write. From masked inputs, grids that support millions of rows, to the cool animation library such as <a href="https://github.com/chenglou/react-motion">react-motion</a> the large and quickly growing community offers a plethora of libraries to avoid duplication of efforts and add value unique to your application.</p><h4>Conclusion</h4><p>In the end every solution is a compromise and with state of our knowledge and technology, I believe that React is currently the best compromise for web development. In the future something better will come along and eat its lunch but until then I’ll stick with React.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb4808c16d62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Of pipes and feeds]]></title>
            <link>https://medium.com/@bobiblazeski/of-pipes-and-feeds-6b443b9713e0?source=rss-1f63bedf8567------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b443b9713e0</guid>
            <category><![CDATA[rethinkdb]]></category>
            <dc:creator><![CDATA[Slobodan Blazeski]]></dc:creator>
            <pubDate>Sat, 06 Jun 2015 13:24:08 GMT</pubDate>
            <atom:updated>2015-06-21T15:08:43.652Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been hearing a lot of good things about RethinkDB and its ReQL query language for a long time, but somehow I never tried it. RethinkDB is in a crowded space of JSON databases and the current king is MongoDB. Its not perfect but I am very pleased working with MongoDB and like its query language. The usefulness of a technology comes from its ecosystem and the MongoDB ecosystem is huge. No matter how good folks at RethinkDB are they simply can’t compete with the behemoth of all MongoDB users, library authors, hosting companies and authors of books and tutorials.</p><p>So in order for new technology to succeed in the marketplace they needed according to Geoffrey Moore a pragmatist in pain. The problem of writing real time web applications is the one that in January 27 ’15 they’ve addressed with the new feature called change time <a href="http://rethinkdb.com/blog/realtime-web/">feeds</a>.</p><p>Before that beside custom in house solutions, writing real time web applications was limited to choosing between <a href="https://www.firebase.com/">firebase</a> platform, which is service only solution something that alienates everybody who prefers to host on their own server and <a href="http://www.meteor.com/">meteor</a>. Meteor is great, if you are writing a real time application from scratch definitely you should consider it, since it offers so many things for end to end development, such as mongo database on both the client and the server, latency compensation, security model, code sharing etc. So I’ve decided to try how much of those goodies I could reproduce with available technologies and least amount of effort.</p><p>For the client I’ve chosen <a href="https://facebook.github.io/react/">ReactJS</a>, as my view layer. I’ve used <a href="https://github.com/koajs/koa">Koa</a>, just because it is small, though you could replace it with express or whatever since it only serves static files. The real-time communication was done using <a href="http://www.socket.io/">socket.io</a> and I’ve used <a href="https://github.com/Reactive-Extensions/RxJS">RxJS</a> to orchestrate the whole thing.</p><h4>The process</h4><p>First I’ve installed RethinkDB and played for a few hours with ReQL language. The installation went perfectly and working with ReQL was great, I especially liked the ReQL web administration page. It has autocomplete, realtime updates and it looks very nice.</p><p>Since I didn’t wanted to meddle with less I put the full css file made by meteor, &amp; created a webpack setup to compile and bundle the jsx files. I decided to just start the meteor example and start porting the generated html code into React components, I only looked at Blaze templates in couple of occasions. Creating the React components was very easy, copy paste, add closing tags to inputs and change class to className. Hooking up socket io was also very easy. Beside the logic in the components RxJS is doing the heavy lifting and it does its job marvelously. Webpack made the code sharing a breeze and Ramda helped with low level functional tasks.</p><h4>The problems</h4><p>The problems were mostly in three areas:</p><p>1st RethinkDB doesn’t work on windows so I had to use Ubuntu virtual machine, and programming under virtual environment is annoying at best. Even on powerful server the experience was very poor.</p><p>2nd I had lot of problems with the React router. Either I don’t understand it or it doesn’t fit my model of thinking. I almost started to write my own router, luckily I avoided the temptation and learned to live with the ugliness.</p><p>3rd My lack of experience with RxJS especially on the server. RxJS is very powerful but it requires specific way of thinking. I still haven’t trained my brain to think in streams in a satisfactory way. I feel that I’m abusing BehaviourSubject where other approach might be better. I decided to use Async for the database setup since that is what I know and I was impatient to dig in RxJS literature.</p><h4>Verdict</h4><p>The source of the end result could be found <a href="https://github.com/bobiblazeski/rio/">here</a>. It still lacks polish but its usable. I’m pleasantly surprised how much real time functionality could you achieve with so little effort. RethinkDB change feeds work like charms, and seeing your application updates in real time looked very nice. Hope to see that windows port released as soon as possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b443b9713e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional reactive interfaces]]></title>
            <link>https://medium.com/@bobiblazeski/functional-reactive-interfaces-e8de034de6bd?source=rss-1f63bedf8567------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8de034de6bd</guid>
            <dc:creator><![CDATA[Slobodan Blazeski]]></dc:creator>
            <pubDate>Fri, 27 Mar 2015 19:05:47 GMT</pubDate>
            <atom:updated>2015-03-27T19:26:11.850Z</atom:updated>
            <content:encoded><![CDATA[<h3>Real time with RxJS</h3><blockquote>The future is already here — it’s just not very evenly distributed.<strong> </strong>William Gibson</blockquote><p>Lately it seems that every popular web application is infected with phantom unread notification bug. You see the unread messages flashing over the notifications button, you place the cursor over it and there is none. The flash disappears, only to reappear randomly after a while.</p><p>There are many components in the modern single page web application, enabling multitude of user interactions, with data coming asynchronously from many sources. With every new functionality application state grows exponentially and becomes harder and harder to keep in sync. Functional reactive programming claims to be the hero coming to the rescue, and there’s been a lot of JavaScript libraries to fit the bill. After looking through some demonstration videos and sampling the documentation and examples of the most popular FRP libraries I&#39;ve decided to give <a href="http://reactive-extensions.github.io/RxJS/">RxJS</a> a try.</p><p>Since I can’t understand anything nontrivial without seeing the need for it I decided to make a sample application with RxJS, using React as my view framework under the Meteor platform. I wanted to see how hard is to make a single view that integrates form entry, table, sorting , filtering and few charts. The rule of the game was that everything must work together in real time.</p><h4>Setup</h4><p>The use of Meteor in my example was limited to compiling React JSX syntax, providing useful packages, and bundling the resulting code into one cohesive solution. Below are the packages used:</p><pre>bobiblazeski:jsx #compiles jsx templates<br>twbs:bootstrap # getbootstrap.com<br>kevohagan:ramda # <a href="http://ramdajs.com/">http://ramdajs.com/</a><br>simoes:d3plus # <a href="http://d3plus.org/">http://d3plus.org/</a></pre><p><a href="https://atmospherejs.com/">Atmosphere</a> lacks RxJS package, so I drop it at /compatibility folder together with <a href="http://fastly.github.io/epoch/">epoch</a> where all the code that is unprepared to work with meteor is placed.</p><h4>Drawing the interface</h4><p>I started by drawing static interface with bootstrap and React.</p><p><strong>First row : c</strong>ontains tree map displaying census regions of the currently selected clients and real time bar chart displaying all data for the all selections.</p><p><strong>Second row</strong>: contains text search, results page size, page navigation.</p><p><strong>Third row</strong>: contains sort button groups for each client field, and start stop button for automatic entering of new clients.</p><p><strong>Fourth row</strong>: contains table displaying current page results and the form for manually entering new clients.</p><h4>Adding logic</h4><p>Wiring the logic with RxJS was surprisingly easy. The most complicated piece of code is the form where I enable the submit button only when all the fields are entered, and email is valid and haven’t been used by any other user. Combine latest works like a charm and fits well with my model of thinking.</p><p>Charts are one other interesting place where I had to sample the results, since I’m depending on external libraries to do the actual drawing I decided to sample the data every 2 seconds. Quick Google search suggested to use an interval.</p><p>I&#39;ve started with flux like architecture with store and actions but actually the hardest things for me was deciding what to put where, and there was lot of duplicate code in the actions that was just calling on next without doing any work, since I didn&#39;t use the server I simply put everything in the store.</p><h4>Problems</h4><p>My problems was more stylistic then real. I was spending more time thinking where to put the observable, and feeling dirty that, god forbid, I’m using it like a global variables. Making the actual application logic work was very quick.</p><p>The only real problems with RxJS was when I changed the format of the data stored in the observable. It happened many times when I re-factored the value of the search filter, stack trace simply disappeared and I had no clue where the error originates. I learned quickly to do re-factor incrementally and rely on Meteor restarting the application.</p><h4>Conclusion</h4><p>The problem with all those silver bullets that promise to eliminate the state, is that state must go somewhere. In RxJS state is like a series of pipes, with your data flowing through them like water. And all that plumbing is visible, nay observable, and you can work and reason with very easily. It just requires different approach of thinking. And the best thing is RxJS is not an all or nothing proposition. You could use it as part of a single component to handle the heavy lifting for some convoluted logic, or it could orchestrate the whole application, the choice is all yours.</p><p>In the end working with RxJS was a mind bending but very pleasant experience.</p><p>References:</p><pre>My sample application <a href="http://rxjs-react.meteor.com/">demo</a> and <a href="https://github.com/bobiblazeski/rxjs-react">source</a> code.<br>RxJS <a href="https://github.com/Reactive-Extensions/RxJS">https://github.com/Reactive-Extensions/RxJS</a><br>Meteor <a href="https://www.meteor.com/">https://www.meteor.com/</a><br>React <a href="https://facebook.github.io/react/">https://facebook.github.io/react/</a><br>d3plus <a href="http://d3plus.org/">http://d3plus.org/</a><br>epoch <a href="http://fastly.github.io/epoch/real-time/#bar">http://fastly.github.io/epoch/real-time/#bar</a><br>RxJS at Netflix <a href="https://www.youtube.com/watch?v=XRYN2xt11Ek">https://www.youtube.com/watch?v=XRYN2xt11Ek</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8de034de6bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tacit Ramda]]></title>
            <link>https://medium.com/@bobiblazeski/tacit-ramda-c914775ff4b1?source=rss-1f63bedf8567------2</link>
            <guid isPermaLink="false">https://medium.com/p/c914775ff4b1</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ramda]]></category>
            <dc:creator><![CDATA[Slobodan Blazeski]]></dc:creator>
            <pubDate>Sat, 07 Mar 2015 23:21:50 GMT</pubDate>
            <atom:updated>2015-03-11T10:12:53.884Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Some programming languages, especially among those which haven&#39;t gained great popularity, are puzzles. <strong>James Hague</strong> (<a href="http://prog21.dadgum.com/38.html">Puzzle Languages</a>)</blockquote><p>Functional programming in JavaScript took a foothold with <a href="http://underscorejs.org/">Underscore</a>, which as of today March 7th 2015, is the most depended package on npm, fallowed by <a href="https://lodash.com/">Lodash</a> as #3. Both Jeremy Ashkenas and John-David Dalton did a great job bringing functional flavor to the JavaScript world, for that I’m very grateful.</p><p>Lately I&#39;ve been playing a lot with <a href="http://ramdajs.com/">Ramda</a>, JavaScript library that promises purer functional style wrapped in a practical package that could be used in your daily projects. Plus I have a bitter sweet relationship with its authors, who never gave me what I&#39;ve asked, but they always delivered what I need.</p><p>Ramda arguments are flipped for the reason best presented by Brian Lonsdorf talk <a href="https://www.youtube.com/watch?v=m3svKOdZijA">Hey Underscore, You’re Doing It Wrong!</a> and its functions are partially applied by default. Together with lack of optional arguments and no dispatching on type Ramda enables writing code in tacit aka pointfree style. Those things though not new, remained in the domain of the experimental and academic libraries.</p><p>You could find Ramda at <a href="http://ramdajs.com/">http://ramdajs.com/</a> which for convenience has an online REPL that enables you to try the below code examples at <a href="http://ramdajs.com/repl/">http://ramdajs.com/repl/</a> . OK enough talking, lets start coding.</p><h4>Curry</h4><p>Ramda functions are automatically curried, thus enabling you to create new functions by omitting arguments.</p><pre>var add5 = R.add(5); // <a href="http://ramdajs.com/docs/#add">http://ramdajs.com/docs/#add</a><br>add5(4) //=&gt; 9</pre><pre>var double = R.multiply(2)<br>double(6);//=&gt; 12</pre><p>And if you need your own functions to be curryed use R.curry</p><pre>// <a href="http://en.wikipedia.org/wiki/Heron%27s_formula">http://en.wikipedia.org/wiki/Heron%27s_formula</a> <br>var heron = R.curry(function heron(a,b,c){<br>   var s= (a+b+c)/2;<br>   return Math.sqrt(s*(s-a)*(s-b)*(s-c));<br>});<br>R.map(heron(3,4),[5,7,9])//=&gt; [6,0,NaN]</pre><p>The first issue with currying comes with anti-commutative functions, such as divide, subtract &amp; modulo. In curried form its usually the first argument that we want to omit. For such uses Ramda provides R.__ placeholder</p><pre>var minus5 = R.subtract(R.__,5);<br>minus5(9) //=&gt; 4</pre><pre>var half= R.divide(R.__,2);<br>half(6); //=&gt; 3</pre><pre>var isOdd = R.modulo(R.__,2);<br>isOdd(3) //=&gt; 1</pre><p>Though its usage is consistent throughout the library this R.__ placeholder introduces some kind of ugliness thus having a version with flipped arguments looks better for this trio of functions.</p><p>For this purpose Ramda provides <a href="http://ramdajs.com/docs/#flip">R.flip</a> which returns a new function much like the supplied one, except that the first two arguments’ order is reversed.</p><pre>var subtractBy = R.flip(R.subtract)<br>var minus5 = subtractBy(5)<br>minus5(9) //=&gt; 4</pre><pre>var divideBy = R.flip(R.divide)<br>var half = divideBy(2)<br>half(6); //=&gt; 3</pre><pre>var moduloBy = R.flip(R.modulo)<br>var isOdd = moduloBy(2)<br>isOdd(3) //=&gt; 1</pre><p>Ramda actually had above three functions in the previous versions but they were omitted to keep the library leaner.</p><h4>Classics</h4><p>The most well known higher order functions map, filter &amp; reduce are curried as well in Ramda.</p><pre>// double elements<br>var doubleAll = R.map(R.multiply(2))<br>doubleAll([1,2,3]) //=&gt; [2,4,6]</pre><pre>var odds = R.filter(R.modulo(R.__,2))<br>odds([1,2,3,4]) //=&gt; [1,3]</pre><pre>var flatten = R.reduce(R.concat,[]);<br>flatten([[1,2],[3,4]])//=&gt;[1,2,3,4]</pre><h4>Compose</h4><p>Now that we covered the basics lets get to the part where we are creating more interesting functions. Our first tool is compose which creates a new function that runs each of the functions supplied as parameters in turn, passing the return value of each function invocation to the next function invocation, beginning with whatever arguments were passed to the initial invocation. Yes I&#39;ve copy pasted the documentation but example will clear the concept.</p><pre>var triplePlusOneAbs = R.compose(Math.abs,R.add(1),R.multiply(3))<br>triplePlusOneAbs(-2) //=&gt; 5<br>// which is more or less<br>function triplePlusOneAbs(x){<br>    return Math.abs(R.add(1,R.multiply(3,x)));<br>}<br>triplePlusOneAbs(-2) //=&gt; 5</pre><p>Note that rightmost function could take several arguments, the rest are limited to one.</p><pre>var rectanglePerimeter = R.compose(R.multiply(2),R.add)<br>rectanglePerimeter(2,3);//=&gt;10</pre><p>One nice technique when using pure functions is being able to memoize the results.</p><pre>var oneToN = R.compose(R.range(1),R.add(1))<br>oneToN(5) //=&gt; [1,2,3,4,5]</pre><pre>var factorial = R.memoize(R.compose(R.product,oneToN))<br>factorial(5) //=&gt; 120</pre><p>How about splitting the string into uppercase tokens</p><pre>var tokenize = R.compose(R.split(&#39; &#39;),R.toUpper);<br>tokenize(&quot;Mary had a little lamb&quot;)<br>//=&gt;[&#39;MARY&#39;,&#39;HAD&#39;,&#39;A&#39;,&#39;LITTLE&#39;,&#39;LAMB&#39;]</pre><p>Converge</p><p>Converge also known as monadic fork in the J world is probably the most well known of the higher order forms</p><pre>var avg = R.converge(R.divide,R.sum,R.length)<br>avg([1,2,3,4,5,6,7])//=&gt; 4</pre><pre>var isDuplicate = R.converge(R.not(R.eq),R.indexOf,R.lastIndexOf)<br>isDuplicate(1,[2,1,3,1,6]) //=&gt; true<br>isDuplicate(2,[2,1,3,1,6]) //=&gt; false</pre><p>The best explanation how it works is probably to see how its implemented</p><pre>var converge = R.curry(function(f,g,h,x,y) {<br>   return f(g(x,y),h(x,y));<br>});</pre><p>The other higher order form I’ve found quite useful is monadic noun fork</p><pre>var monadNounFork = R.curry(function monadicNounFork(f, g,x, y){<br>  return f(g(x),y);<br>});</pre><pre>var listPlusN = monadNounFork(R.map,R.add);<br><em>listPlusN(10, [1,2,3,4,5]);//=&gt; [</em>11,12,13,14,15<em>]</em></pre><p>But let’s try it on accessing data. Here’s an example I’ve shamelessly ripped of the <a href="https://frontendmasters.com/courses/functional-javascript/">Hardcore Functional Programming in JavaScript</a>. We have an array containing articles. We want to create a function that extracts all the author names and another one that checks is someone an author.</p><pre>var monadNounFork = R.curry(function monadNounFork(f, g,x, y){<br>  return f(g(x),y);<br>});</pre><pre>var articles = [<br> {<br>        title: &#39;Everything Sucks&#39;,<br>        url: &#39;<a href="http://do.wn/sucks.html&#39;">http://do.wn/sucks.html&#39;</a>,<br>        author: {<br>            name: &#39;Debbie Downer&#39;,<br>            email: &#39;<a href="/service/mailto:debbie@do.wn">debbie@do.wn</a>&#39;<br>        }<br>    },<br>    {<br>        title: &#39;If You Please&#39;,<br>        url: &#39;<a href="http://www.geocities.com/milq&#39;">http://www.geocities.com/milq&#39;</a>,<br>        author: {<br>            name: &#39;Caspar Milquetoast&#39;,<br>            email: &#39;<a href="/service/mailto:hello@me.com">hello@me.com</a>&#39;<br>        }<br>    }<br>];<br>var authors = R.map(R.compose(R.prop(&#39;name&#39;), R.prop(&#39;author&#39;))); <br>authors(articles); <br>// =&gt;[&#39;Debbie Downer&#39;,&#39;Caspar Milquetoast&#39;]<br>var isAuthor = R.flip(monadNounFork(R.flip(R.contains), authors));<br>isAuthor(&#39;New Guy&#39;, articles)<br>isAuthor(&#39;Caspar Milquetoast&#39;, articles)</pre><p>The higher form worked and we achieved our goal without using parameters. However all those flips are sign of a code smell. We are trying to fit tacit style into the problem where the tacit solution isn’t obvious. That makes it a puzzle.</p><p>As a parting gift I’ll left with you with an exercise for the reader.</p><p>We have a list of elements, some are duplicates. We’re trying out how to find the duplicate elements and increase a counter value by 1 for each instance of the element found. The list consists of lists with two elements, the first being the incremental counter, the second being the string sought.</p><p><a href="http://www.nsl.com/papers/kisntlisp.htm">http://www.nsl.com/papers/kisntlisp.htm</a></p><pre>var example= [[1,&quot;one&quot;],[1,&quot;two&quot;],[1,&quot;three&quot;],[1,&quot;one&quot;],[1,&quot;four&quot;],[1,&quot;two&quot;]];<br>var brunberg = R.compose(R.mapObj(R.length),R.groupBy(R.nth(1)))<br>brunberg(example)<br>// =&gt;&quot;{&quot;one&quot;:2,&quot;two&quot;:2,&quot;three&quot;:1,&quot;four&quot;:1}&quot;</pre><p>Your solution should produce</p><pre>var sought = [[2,&quot;one&quot;],[2,&quot;two&quot;],[1.&quot;three&quot;],[1,&quot;four&quot;]];</pre><p>Update:</p><p>As suggested by Scott Sauyer @CrossEye there is a simpler definition for isAuthor using R.useWith :</p><pre>var isAuthor = R.useWith(R.contains, R.identity, authors);</pre><p>Here’s my solution for the final exercise:</p><pre>var example= [[1,”one”],[1,”two”],[1,”three”],[1,”one”],[1,”four”],[1,”two”]];<br>var brunberg = R.compose(R.map(R.reverse),R.toPairs,R.mapObj(R.length),R.groupBy(R.nth(1)))<br>JSON.stringify(brunberg(example)); <br>// =&gt; [[2,&quot;one&quot;],[2,&quot;two&quot;],[1,&quot;three&quot;],[1,&quot;four&quot;]]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c914775ff4b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>