<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Akshay Nair</title>
    <description>The latest articles on DEV Community by Akshay Nair (@phenax).</description>
    <link>https://dev.to/phenax</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F128235%2F10a4825b-defe-432c-9e47-3a29b066202a.png</url>
      <title>DEV Community: Akshay Nair</title>
      <link>https://dev.to/phenax</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/phenax"/>
    <language>en</language>
    <item>
      <title>JS Magic Tricks to impress your friends</title>
      <dc:creator>Akshay Nair</dc:creator>
      <pubDate>Fri, 29 Mar 2019 18:30:00 +0000</pubDate>
      <link>https://dev.to/phenax/js-magic-tricks-to-impress-your-friends-1f81</link>
      <guid>https://dev.to/phenax/js-magic-tricks-to-impress-your-friends-1f81</guid>
      <description>&lt;p&gt;My name is Houdini J.S. Magnifico. What I’m about to perform here are a set of illusions and magic tricks that are sure to blow your mind! So prepare to be amazed!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The tricks shown here are performed by trained professionals. Do not attempt these stunts at home. Do it at your office.Viewer discretion is advised.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let’s-a go!&lt;/p&gt;




&lt;h1&gt;
  
  
  For my first trick, I’m gonna make this function… DISAPPEAR!
&lt;/h1&gt;

&lt;p&gt;This is my totally normal, nothing weird about it, stop asking me, function.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--mMRYlcYu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/fn.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--mMRYlcYu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/fn.jpg" alt="typeof function"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Let me just wave Brendan Eich’s mouse pad over it for a bit… and… BOOM!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3FIfVtWj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/fn-1.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3FIfVtWj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/fn-1.jpg" alt="typeof function"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;GONE! The function is not a function anymore. Schrodinger’s function has dissappeared!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;audience applauds&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Thank you! Thank you!&lt;/p&gt;

&lt;h4&gt;
  
  
  Here’s how it works
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const innocentTotallyNormalFunction = (() =&amp;gt; {}).apply.bind();
// Works with any method's bind();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Weird right? It’s called JavaScript and a lot of people use this in production. The reason this doesn’t work is because .apply method expects the context of a function but .bind gives it undefined as the context. this.means that the apply method doesn’t know which function it is trying to apply. Then the apply method has an identity crisis and everything goes to shit.&lt;/p&gt;




&lt;h1&gt;
  
  
  Magic list
&lt;/h1&gt;

&lt;p&gt;Here I have a function that clones an array. Perfectly normal, production ready code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const clone = list =&amp;gt; list.reduce((newList, item) =&amp;gt; [...newList, item], []);

// Another clone implementation you can use is,
const clone = Object.values;

// Or if you wanna go old school...
const clone = list =&amp;gt; {
  const newList = [];

  for(let index in list) {
    newList.push(list[index]);
  }

  return newList;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s an ordinary list with nothing fishy going on inside&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4lF2_kPe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/list.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4lF2_kPe--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/list.png" alt="typeof function"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I’m just gonna casually use the clone function to copy the list and check the length of the newly created list…&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--sX_hQxze--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/list-clone.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--sX_hQxze--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/list-clone.png" alt="typeof function"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Magic!!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The list is no longer 23 items long. 23 to 1! Next-gen compression algorithm, question mark? Or is it just magic?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--56ZHaeI3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://phenax.github.io/img/blog/jsmagic/how-did-you-do-that.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--56ZHaeI3--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://phenax.github.io/img/blog/jsmagic/how-did-you-do-that.gif" alt="typeof function"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Well, here's how it all went down
&lt;/h4&gt;

&lt;p&gt;The concept behind this is one that not many developers are familiar with. Array holes, also called empty slots are points in an array that are empty. No, I’m not talking about undefined or null or 0. Just empty.&lt;/p&gt;

&lt;p&gt;Ref: &lt;a href="https://2ality.com/2015/09/holes-arrays-es6.html"&gt;Array holes/empty slots&lt;/a&gt;, &lt;a href="https://2ality.com/2012/06/dense-arrays.html"&gt;Sparse arrays&lt;/a&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Array(5) // &amp;gt;&amp;gt; [&amp;lt;empty x 5&amp;gt;]

// In ES2015, you can also do
[,,,,,] // &amp;gt;&amp;gt; [&amp;lt;empty x 5&amp;gt;]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This creates an array of 5 items but without any values. But javascript doesn’t use undefined as the default values tho. It instead creates empty slots (holes) in the arrays but keeps given the length. So when you copy it using the reduce method, it doesn’t iterate over the empty slots. So the newly generated array is shorter.&lt;/p&gt;




&lt;h1&gt;
  
  
  Schrodinger’s magic list
&lt;/h1&gt;

&lt;p&gt;The list we are gonna be working on is document.all which is a list of all nodes in a document.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8xktctJR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/doc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8xktctJR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/doc.png" alt="document.all"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Council of W3C, give me the strength to make this list disappear!!! Boom! Shaa! Waka-Waka Boom!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--8xjybuBB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/doc-typeof.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--8xjybuBB--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/doc-typeof.png" alt="document.all type"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Be Amazed!!&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Go get an MRI scan because your tiny little brain just exploded!&lt;/p&gt;

&lt;h4&gt;
  
  
  Here’s the big reveal!
&lt;/h4&gt;

&lt;p&gt;document.all is a very old and deprecated api that allowed you to iterate over all the nodes rendered to the DOM. The typeof expression returning undefined was by design as a part of deprecation of that non-standard feature. Weird, I know. But that’s just how javascript rolls.&lt;/p&gt;




&lt;h1&gt;
  
  
  Are we Infinity yet?
&lt;/h1&gt;

&lt;p&gt;Let’s take a number, &lt;code&gt;let x: number&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x + 1 === x; // &amp;gt;&amp;gt; true
x + 2 === x; // &amp;gt;&amp;gt; false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;“What just happened?”&lt;/p&gt;

&lt;p&gt;I added 1 to x and the value didn’t change! Then I added 2 to it and… the universe… it changed.&lt;/p&gt;

&lt;h4&gt;
  
  
  Check out how this works
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const x = 1e16; // OR 1 * Math.pow(10, 16) OR 10000000000000000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is by design. It’s documented in IEEE 754-2008. When the number is as large as this, it rounds it up to the nearest even number.&lt;/p&gt;

&lt;p&gt;Ref: &lt;a href="https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules"&gt;Rounding rules section in IEEE 754&lt;/a&gt;&lt;/p&gt;




&lt;h1&gt;
  
  
  Is a “not a number” a number or not a number? Well, it’s NaN of your business
&lt;/h1&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;typeof NaN === 'number' // &amp;gt;&amp;gt; true
NaN !== NaN // &amp;gt;&amp;gt; true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Wut? ‘Not a number’ is a number and ‘Not a number’ is not equal to ‘Not a number’&lt;/p&gt;

&lt;p&gt;Javascript is a magical language&lt;/p&gt;

&lt;h4&gt;
  
  
  Know the trick
&lt;/h4&gt;

&lt;p&gt;NaN is a numeric data type but it behaves as an identity when any mathematical operation is applied to it.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;“But why is NaN === NaN returning false?”&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Because the Gods of Javascript wished so. If either side of === operator is NaN, the operation returns false. Thats just how it works. Don’t question it.&lt;/p&gt;




&lt;h1&gt;
  
  
  Check if your list has more than 1 items
&lt;/h1&gt;

&lt;p&gt;A very complicated problem in programming.&lt;/p&gt;

&lt;p&gt;A normie dev would go ahead and write something like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const hasAtleast2Elements = x =&amp;gt; x.length &amp;gt;= 2;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That solution is 13 characters long. In the modern world of javascript, 13 characters is way too many characters. It is a performance bottleneck.&lt;/p&gt;

&lt;p&gt;Let’s write something more optimized in size&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const hasAtleast2Elements = x =&amp;gt; !isNaN(+x);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There. 10 characters. Much better. We removed &lt;strong&gt;23%&lt;/strong&gt; of our JavaScript! Good job. Less JavaScript is good JavaScript&lt;/p&gt;

&lt;h4&gt;
  
  
  The genius behind this action
&lt;/h4&gt;

&lt;p&gt;We improved our load time by 23% but at what cost?! How does that function even work? Magic?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3ZFWPAs2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://phenax.github.io/img/blog/jsmagic/not-magic-science.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3ZFWPAs2--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://phenax.github.io/img/blog/jsmagic/not-magic-science.gif" alt="document.all"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The + operator applied to a list returns NaN if the number of items in the list is more than 1.&lt;/p&gt;

&lt;p&gt;Why does it do that? Well, type casting. +[] is equal to +[].toString().&lt;/p&gt;

&lt;p&gt;So,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[].toString() === '' // &amp;gt;&amp;gt; +'' === 0
[1].toString() === '1' // &amp;gt;&amp;gt; +'1' === 1
[1, 2].toString() === '1,2' // &amp;gt;&amp;gt; +'1,2' === NaN (Cannot typecast as it is not a number)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;









&lt;p&gt;That’s all for today! Tune in next time to watch Magnifico use magic in production and get fired immediately.&lt;/p&gt;

&lt;p&gt;Now I’m gonna make myself disappear.&lt;/p&gt;

&lt;p&gt;…&lt;/p&gt;

&lt;p&gt;…&lt;/p&gt;

&lt;p&gt;…&lt;/p&gt;

&lt;p&gt;Why is this… Just a second folks… Some technical difficul…&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Poof&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LDO6w26U--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/blaine.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LDO6w26U--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/jsmagic/blaine.jpg" alt="document.all"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>magic</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Grandma's recipes for cooking redux</title>
      <dc:creator>Akshay Nair</dc:creator>
      <pubDate>Fri, 15 Mar 2019 18:30:00 +0000</pubDate>
      <link>https://dev.to/phenax/grandma-s-recipes-for-cooking-redux-4chb</link>
      <guid>https://dev.to/phenax/grandma-s-recipes-for-cooking-redux-4chb</guid>
      <description>&lt;p&gt;Welcome to my Grandma’s Kitchen. I’m your host, the grandson. Let’s start cooking, shall we?&lt;/p&gt;

&lt;p&gt;Disclaimer: Stuff referenced in this post are not my opinions, they are straight up facts. If you disagree, go ahead and give this post 50 slaps (It’s the same button as the clap one. Just click on it more aggressively and it gets marked as a slap). Reader discretion is advised.&lt;/p&gt;

&lt;p&gt;For far too long have we suffered the torture of writing boilerplate code and messy actions. Not anymore. Here are some recipes to cook redux the way my grandma wants you to.&lt;/p&gt;

&lt;p&gt;We are going to be cooking with the following ingredients today -&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/redux-saga/redux-saga"&gt;Redux Saga&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/phenax/redux-utils"&gt;Redux Utils&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/evilsoft/crocks"&gt;Crocks&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/reduxjs/reselect"&gt;Reselect&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://github.com/ramda/ramda"&gt;Ramda&lt;/a&gt; (optional. Add according to taste)&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Spicy hot action names/types
&lt;/h2&gt;

&lt;p&gt;You wouldn’t expect there to be any changes in the way you create action names/types but why not? Go check your action types file. You will find that there is a recurring pattern of the three states. &lt;code&gt;ACTION_PENDING&lt;/code&gt;, &lt;code&gt;ACTION_SUCCESS&lt;/code&gt; and &lt;code&gt;ACTION_FAILURE&lt;/code&gt; (not FAIL because &lt;code&gt;PENDING&lt;/code&gt;, &lt;code&gt;SUCCESS&lt;/code&gt; and &lt;code&gt;FAILURE&lt;/code&gt; have the same number of characters and my grandma likes consistency). And while we are at it we can also learn something from the REST architecture from my grandma’s time and bring the resource/action pattern in here.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;actionTypes&lt;/code&gt; function uses the &lt;code&gt;@resource/ACTION/STATE&lt;/code&gt; convention.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { actionTypes } from '@phenax/redux-utils';

const types = actionTypes({
  DISHES: {
    LIST: ['PENDING', 'SUCCESS', 'FAILURE'],
    ADD: ['PENDING', 'SUCCESS', 'FAILURE'],
  },
  SESSION: {
    INIT: ['PENDING', 'SUCCESS', 'FAILURE'],
  },
});

types.DISHES.ADD.SUCCESS === '@dishes/ADD/SUCCESS'; // true

// Your actions will then look something like
dispatch({
  type: types.DISHES.ADD._,
  payload: {
    name: 'Chicken that tastes like paneer’,
    ingredients: {
      chicken: { count: 1, unit: 'bird' },
      salt: { toTaste: true },
      pepper: { count: 2, unit: 'shakes' },
      milk: { count: 3, unit: 'seconds of pouring' },
    },
  },
});

// The underescore (`._`) is the dispatch that gets picked up by the sagas. Its a default dispatch i.e. stateless dispatch.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Reducer salad
&lt;/h2&gt;

&lt;p&gt;The three state pattern is also seen repeated a lot inside reducers. My grandma keeps telling me “My back hurts when I scroll through long switch-case statements”. So if you haven’t guessed already, we are going to change that too now. We have to care for the elderly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createPartialReducer, mergeReducers } from '@phenax/redux-utils';

const initialState = { loading: false, readyForServing: true, dishes: [], error: '' };

const getLoadingState = state =&amp;gt; ({ readyForServing }) =&amp;gt; ({
  ...state,
  readyForServing,
  loading: true,
});

const addDishReducer = createPartialReducer(types.DISHES.ADD, (state = initialState, action) =&amp;gt; ({
  PENDING: getLoadingState(state),
  SUCCESS: newDish =&amp;gt; ({
    ...state,
    readyForServing: true,
    loading: true,
    dishes: [...state.dishes, newDish],
  }),
  FAILURE: e =&amp;gt; ({
    ...state,
    readyForServing: false,
    loading: true,
    error: e.message,
  }),
}));

// Your regular reducer can be merged with partials
const regularOldReducer = (state = initialState, action) =&amp;gt; {
  switch(action.type) {
    case types.SOMEOTHER.ACTION.PENDING:
      return {
        ...state,
        loading: true,
      };
    case types.SOMEOTHER.ACTION.SUCCESS:
      return {
        ...state,
        loading: false,
        dishes: [],
      };
    case types.SOMEOTHER.ACTION.FAILURE:
      return {
        ...state,
        loading: false,
        dishes: [],
        error: e.message,
      };
  }
};

export default mergeReducers(addDishReducer, regularOldReducer);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The partial reducers allow you to split the reducer into smaller functions based on the resource/action/state convention. You can also use this to show off your rad point-free trick shots.&lt;/p&gt;




&lt;h2&gt;
  
  
  Duck promises
&lt;/h2&gt;

&lt;p&gt;There are 3 different ways to interpret name of this dish. Clue, it’s not a typo (even though it fits perfectly). Another clue, we’re not cooking a duck here. You are correct. Just duck those promises and go with &lt;code&gt;Async&lt;/code&gt; from crocks. (Not to be confused with &lt;code&gt;async/await&lt;/code&gt; which is just a prank that the C# community is playing on us disguised as w3c draft authors). Here's how to use fetch (or any other promise based api) and turn it into a composible, cancellable, lazy Async task. Grandma does not approve laziness but we will use it anyway because GOD DAMMIT, IT'S MY FREAKING COOKING SHOW! GET OUT OF MY ROOM, GRANDMA!&lt;/p&gt;

&lt;p&gt;For you, a simple made-up example of fetching with network timeout. fetchJson is just an Async wrapper for fetch api.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Async from 'crocks/Async';
import { prop, filter, map, either, complement } from 'ramda';
import { fetchJson } from '@phenax/redux-utils/async';

// Some other api call that happens after we get the data from the user
// fetchChefInfo :: a -&amp;gt; Async a
const fetchChefInfo = data =&amp;gt; Async((rej, res) =&amp;gt; setTimeout(() =&amp;gt; res(data), 700));

// fetchServableDishes :: Object * -&amp;gt; Async [User]
const fetchServableDishes = params =&amp;gt; fetchJson('/dishes', params)
  .race(Async.rejectAfter(2000, new Error('Request Timeout')))
  .map(prop('dishes'))
  .map(compose(
    filter,
    complement,
    either(
      prop('isReady'),
      prop('isBurnt'),
    ),
  ));

let task = fetchServableDishes();

// The request has not been sent yet (it's lazy like crazy! Thank you. Thank you.). You can keep composing and chaining stuff
task = task
  .map(map(decorateDish))
  .chain(fetchChefInfo);

// And when you finally decide that you want to make the api call, you can fork it.
// Nothing is executed till you call .fork
task.fork(
  e =&amp;gt; console.error(e),
  activeUsers =&amp;gt; {
    // Do stuff
  },
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Barbecue sagas
&lt;/h2&gt;

&lt;p&gt;Redux saga is the best way to write actions. That is a fact, not an opinion. No need to look it up. Not going to change anything with that but we can add a few ingredients to enhance its flavor. We are also going to use &lt;code&gt;Async&lt;/code&gt; instead of &lt;code&gt;Promise&lt;/code&gt; because my grandma believes you shouldn't make promises you can't keep/manage.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { put } from 'redux-saga/effects';
import { callAsync, putResponse } from '@phenax/redux-utils/saga';

export function* add({ payload }) {
  yield put({ type: types.DISHES.ADD.PENDING, payload: {} });
  const response = yield callAsync(saveNewDish, payload);
  yield putResponse(types.DISHES.ADD, response);
};

export function* list({ payload }) {
  yield put({ type: types.DISHES.LIST.PENDING, payload: {} });
  const response = yield callAsync(fetchServableDishes);
  yield putResponse(types.DISHES.LIST, response);
};

export default function* root() {
  yield all([takeLatest(types.DISHES.ADD._, add)]);
  yield all([takeLatest(types.DISHES.LIST._, list)]);
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yield putResponse(types.DISHES.LIST, response);
// is just a shorthand for
yield put(response.cata({
  Success: data =&amp;gt; ({ type: types.DISHES.LIST.SUCCESS, payload: data }),
  Failure: error =&amp;gt; ({ type: types.DISHES.LIST.FAILURE, payload: error }),
}));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Selector noodles
&lt;/h2&gt;

&lt;p&gt;Selectors allow you to derive your data from the state and memoize the operation. We are going to use reselect for this and we’re also gonna sprinkle some ramda in there according to taste. You can use lodash too but why would you do something like that? Ramda is to lodash what a smart watch is to a tin-can telephone.&lt;/p&gt;

&lt;p&gt;Grandma: “Back in my day, underscore was pretty popular. It was like…”.&lt;/p&gt;

&lt;p&gt;Yeah grandma, we get it, you’re old. Now shut up and let me show these people some selector action.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createSelector } from "reselect";
import { pathOr, prop, __, map } from 'ramda';

// selectBurntDishes :: { dishes :: { dishIds :: [String], items :: Object Profile } } -&amp;gt; [String]
export const selectBurntDishes = createSelector(
  pathOr({}, ['dishes', 'items']),
  pathOr([], ['dishes', 'dishIds']),
  (items, dishIds) =&amp;gt; dishIds.filter(compose(
    prop('isBurnt'),
    map(prop(__, items)),
  )),
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now you can use it anywhere…&lt;/p&gt;

&lt;p&gt;In you component’s mapStateToProps,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mapStateToProps = state =&amp;gt; ({
  burntDishes: selectBurntDishes(state),
});

export default connect(mapStateToProps)(ListBurntDishes);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In your sagas,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function* mySaga() {
  const burntDishes = yield select(selectBurntDishes);
  // Do stuff with those ids
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Doesn’t that look pretty? If you’re new to the point-free way, you may feel like you just watched a french movie without subtitles but trust me, this is worth the confusing first few days.&lt;/p&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Old ideas and opinions are what new ones are born from. Grandma’s recipes were great and they’ve come out of experience that doesn’t mean we have to keep making the same thing a billion times. Small (and sometimes large) migrations are a good thing.&lt;/p&gt;

&lt;p&gt;So let’s summarise. What did we learn today?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use grandma’s favorite convention of &lt;code&gt;@resource/ACTION/STATE&lt;/code&gt; for your action types&lt;/li&gt;
&lt;li&gt;The elderly hate long switch case statements&lt;/li&gt;
&lt;li&gt;Duck promises because &lt;code&gt;Async&lt;/code&gt; rocks!&lt;/li&gt;
&lt;li&gt;Sagas are the freakin best!!&lt;/li&gt;
&lt;li&gt;Memoize those selectors for a better tomorrow&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These are all solutions to the small yet annoying inconveniences that I ran into while working on a personal project of mine. I’m collecting all of the tiny helpers over at &lt;a href="https://github.com/phenax/redux-utils"&gt;@phenax/redux-utils&lt;/a&gt;. The project is not done yet so the library will be getting more updates. PRs are welcome!!&lt;/p&gt;

&lt;p&gt;Hope these ideas help you write some tasty code.&lt;/p&gt;

</description>
      <category>redux</category>
      <category>react</category>
      <category>ramda</category>
      <category>crocks</category>
    </item>
    <item>
      <title>PureFunctionalJS - Sum Types In JavaScript</title>
      <dc:creator>Akshay Nair</dc:creator>
      <pubDate>Thu, 14 Mar 2019 18:30:00 +0000</pubDate>
      <link>https://dev.to/phenax/purefunctionaljs-sum-types-in-javascript-55ae</link>
      <guid>https://dev.to/phenax/purefunctionaljs-sum-types-in-javascript-55ae</guid>
      <description>&lt;p&gt;JavaScript has a very bad reputation in most developer communities. So much so that, “Writing cleaner and safer JavaScript…” in the title may already seem a bit redundant to most readers. A lot of that has to do with loose typing, invalid values and the horrible chain of ternary expressions or heaven forbid, if statements to handle them. With JavaScript, all functions run on the concept of “pretend what you are getting is what you asked for”. If the value is not valid for the kind of operation you are running on it, well, too bad. To save yourself from this, you can write run-time validations, add type-checks, etc but the core of the problem is till left largely unsolved.&lt;/p&gt;




&lt;h2&gt;
  
  
  Let’s learn from Haskell
&lt;/h2&gt;

&lt;p&gt;Functional programming languages like Haskell have a clear solution for this. Sum Types! Sum Type (or Tagged Union) is an Algebraic Data Type which describes values that can take on several different types. Popular examples in haskell are the Maybe monad (for handling the validity of values) and the Either monad (for error handling).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--1KCoSKAE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/enum-fp/haskell.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--1KCoSKAE--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/enum-fp/haskell.jpeg" alt="lost your monads?"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Don’t worry. Maybe, I don’t know anything about monads Either (see what I did there?). All we need to know is that a Sum Type is a has multiple named constructors.&lt;/p&gt;

&lt;p&gt;In Haskell, a Sum type looks something like this -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data MetalGenre = ProgMetal | DeathCore

scream :: MetalGenre -&amp;gt; IO ()
scream genre = putStrLn $ case genre of
  ProgMetal -&amp;gt; "Oh!"
  DeathCore -&amp;gt; "BleaAaAHHH!!"

main :: IO()
main = scream ProgMetal
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, MetalGenre is the type and ProgMetal, DeathCore are constructors of that type.&lt;/p&gt;

&lt;p&gt;A really popular and useful example of a Sum type in the functional world is the Maybe type. In Haskell, Maybe is a monad that wraps a value and helps you make sure that invalid values are not acted upon, thus allowing you to write safer functions.&lt;/p&gt;

&lt;p&gt;This is what Maybe’s definition looks like in Haskell -&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;data Maybe = Just a | Nothing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now here, all valid values will be wrapped in a Just and all invalid values will be wrapped in a Nothing. This way, we can handle invalid values in a clean and elegant way and be sure of the fact that the function is only called for the valid values.&lt;/p&gt;

&lt;p&gt;You might be thinking, “But isn’t this only possible because Haskell is a statically typed beauty and JavaScript is the spawn of satan?”. Maybe it isn’t. (The joke’s getting old now)&lt;/p&gt;




&lt;h2&gt;
  
  
  EnumFP
&lt;/h2&gt;

&lt;p&gt;Shameless self-plug alert!&lt;/p&gt;

&lt;p&gt;I have a library to help with that! (Said every JavaScript developer ever).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/phenax/enum-fp"&gt;EnumFP&lt;/a&gt; (PRs welcome)&lt;/p&gt;

&lt;p&gt;EnumFP is a simple and light-weight way to create Sum types in JavaScript. Inspired by the awesomeness of Haskell, the library is written with safety in mind.&lt;/p&gt;

&lt;p&gt;This is what the metal genre example would look like with EnumFP.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const MetalGenre = Enum(['ProgMetal', 'DeathCore'])

const scream = compose(console.log, MetalGenre.cata({
  ProgMetal: () =&amp;gt; "Oh!",
  DeathCore: () =&amp;gt; "BleaAaAHHH!!",
}));

scream(MetalGenre.ProgMetal());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h2&gt;
  
  
  Maybe, maybe?
&lt;/h2&gt;

&lt;p&gt;The concept of what a Maybe does is more important than the implementation itself. Containing a value in a way that allows you to perform a set of operations on the container and not worry about the validity of the input is what Maybe is about.&lt;/p&gt;

&lt;p&gt;You can implement a simple Maybe and a couple of utility functions using EnumFP. EnumFP also allows you to add argument descriptions. This example uses the caseOf function which is like match but for partial application).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Maybe = Enum({ Just: ['value'], Nothing: [] });

// fmap :: (a -&amp;gt; b) -&amp;gt; Maybe a -&amp;gt; Maybe b
const fmap = fn =&amp;gt; Maybe.cata({
  Just: compose(Maybe.Just, fn),
  Nothing: Maybe.Nothing,
});

// mjoin :: Maybe Maybe a -&amp;gt; Maybe a
const mjoin = Maybe.cata({
  Just: x =&amp;gt; x,
  Nothing: Maybe.Nothing,
});

// chain :: (a -&amp;gt; Maybe b) -&amp;gt; Maybe a -&amp;gt; Maybe b
const chain = fn =&amp;gt; compose(mjoin, fmap(fn));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here,&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;fmap&lt;/strong&gt; returns a new Maybe and runs the function over the value inside, in case of Just and ignores a Nothing. (Like Array.prototype.map)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;mjoin&lt;/strong&gt; unwraps a given nested Maybe. Because many monads like Maybe, are agnostic about the value inside, you can put the monad inside another monad (That’s what shesaid) (Like Array.prototype.flatten)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;chain&lt;/strong&gt; maps over the Maybe and then flattens the resulting nested Maybe. (Like Array.prototype.flatMap).&lt;/p&gt;

&lt;p&gt;Let’s use this and write a function that accepts a User instance and gives you the first name without throwing an error for invalid user or invalid name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// head :: [a] -&amp;gt; Maybe a
const head = arr =&amp;gt; (arr.length ? Maybe.Just(arr[0]) : Maybe.Nothing());

// prop :: String -&amp;gt; Object a -&amp;gt; Maybe a
const prop = key =&amp;gt; obj =&amp;gt; key in obj ? Maybe.Just(obj[key]) : Maybe.Nothing();

// trim :: String -&amp;gt; String
const trim = str =&amp;gt; str.trim();

// split :: String -&amp;gt; String -&amp;gt; [String]
const split = seperator =&amp;gt; str =&amp;gt; str.split(seperator);

// safeUser :: User -&amp;gt; Maybe User
const safeUser = user =&amp;gt; isUserValid(user) ? Maybe.Just(user) : Maybe.Nothing();

// getFirstName :: User -&amp;gt; Maybe String
const getFirstName = compose(
    chain(head), // Maybe [String] -&amp;gt; Maybe String
    fmap(split(' ')), // Maybe String -&amp;gt; Maybe [String]
    fmap(trim), // Maybe String -&amp;gt; Maybe String
    chain(prop('name')), // Maybe User -&amp;gt; Maybe String
    safeUser, // User -&amp;gt; Maybe User
);

Maybe.match(getFirstName(user), {
    Just: name =&amp;gt; console.log('My name is', name),
    Nothing: () =&amp;gt; console.log('Whats in a name?'),
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, we first convert the user to a safe user by wrapping it in a Maybe. Then we get the user’s name using the prop function. The prop and head functions here, instead of returning the value, wraps the value in a Maybe. This is why to map it and then unwrap it, we use chain instead of fmap.&lt;/p&gt;




&lt;h2&gt;
  
  
  Working with React
&lt;/h2&gt;

&lt;p&gt;Yes, EnumFP works well with react! (Jumping from one over-populated community to the next).&lt;/p&gt;

&lt;p&gt;With the new react hooks being introduced in 16.8, it would be a sin not to mention it here. EnumFP ships with a useReducer hook which is a simple wrapper around react’s useReducer.&lt;/p&gt;

&lt;p&gt;Don’t want to upgrade to 16.8? Do you still watch reruns of Seinfeld? Want to wait for your grand-children to help you with the upgrade… and… walking?&lt;/p&gt;

&lt;p&gt;No worries. There’s an HOC available as well.&lt;/p&gt;

&lt;p&gt;You can find out more about integrations with react here.&lt;/p&gt;

&lt;p&gt;And this is not limited to just component state tho. You can use Sum Types to work with any kind of enumerable state values. From handling Success, Pending and Failure states for any action to containing values based on it’s type or validity. Sum Types are here to clean up all of that.&lt;/p&gt;




&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This is just the tip of the iceberg. There are a lot more of these amazing ideas hidden in the world of functional programming, waiting to move to other languages. Being a part of the JavaScript community for a while has made me realise that it’s not all bad. What we lack in language features and standard library, we make up for in the variety of libraries just an npm install away, and the strong community constantly working towards “Making JS great again”. So let’s build a wall together between us and bad code. Covfefe.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--a3wTLDND--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/enum-fp/trump.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--a3wTLDND--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://phenax.github.io/img/blog/enum-fp/trump.jpg" alt="Covfefe"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>sum</category>
      <category>union</category>
      <category>enum</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
