<?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 Waleola Akinsanmi on Medium]]></title>
        <description><![CDATA[Stories by Waleola Akinsanmi on Medium]]></description>
        <link>https://medium.com/@spykins?source=rss-4e8a96d870f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8ldJ84Vh6QedLgPRnd9KgA.jpeg</url>
            <title>Stories by Waleola Akinsanmi on Medium</title>
            <link>https://medium.com/@spykins?source=rss-4e8a96d870f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:05:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@spykins/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[Better Code: Generics in Typescript — Monkey Work, Baboon Chop]]></title>
            <link>https://medium.com/@spykins/better-code-generics-in-typescript-monkey-work-baboon-chop-50e6f84bad6a?source=rss-4e8a96d870f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/50e6f84bad6a</guid>
            <category><![CDATA[strongly-typed]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[generic-programming]]></category>
            <dc:creator><![CDATA[Waleola Akinsanmi]]></dc:creator>
            <pubDate>Sun, 24 May 2020 19:25:20 GMT</pubDate>
            <atom:updated>2020-05-24T20:18:29.218Z</atom:updated>
            <content:encoded><![CDATA[<h3>Better Code: Generics in Typescript — Monkey Work, Baboon Chop</h3><p>The phrase “Monkey Work, Baboon chop” is used in my country and I will decipher what it means at the end of this article. Meanwhile, before we dive into Generic, let’s take a step back to see the headache we avoid by using a strictly typed language.</p><h3>What is Strongly and Loosely typed language?</h3><blockquote>According to <a href="https://en.wikipedia.org/wiki/Strong_and_weak_typing">Wikipedia</a>: Generally, a strongly typed language has stricter typing rules at compile time, which implies that errors and exceptions are more likely to happen during compilation. Dynamically typed languages (where type checking happens at run time) can also be strongly typed. Most of these rules affect variable assignment, return values and function calling.</blockquote><blockquote>A weakly typed language has looser typing rules and <strong>may produce unpredictable results</strong> or may perform implicit type conversion at runtime. A different but related concept is latent typing.</blockquote><p>If this doesn’t make so much sense to you, we are in the same boat but let’s take a look at examples in Javascript.</p><pre>const addValue = (a, b) =&gt; a + b;</pre><p>Can you think about the problem with the Lamda function?</p><ul><li>Javascript v8 engine doesn’t know what ‘a’ and ‘b’ are</li><li>Javascript v8 engine doesn’t know what the function will return</li></ul><p>Now let’s use this function as a client.</p><pre>console.log(addValue(2,3));   // prints 5</pre><pre>console.log(addValue(&quot;2&quot;,&quot;3&quot;)); // prints 23</pre><pre>console.log(addValue(&#39;2&#39;, 3)) // prints 23</pre><p>Imagine if you are getting a JSON payload from the server and you need to perform computation on it, you can quickly run into unexpected results because Javascript is a loose language.</p><p>Let’s write that function in Typescript</p><pre>const addValue = (a: number, b: number) =&gt; a + b;</pre><p>Sweet! now if we try to use the same code with the console log above, the interpreter will yell at us, because it is expecting a number and we are passing two parameters of type string in second and third log.</p><p>Well, this is good but it is still bad. Hmmm!, we now have control over what our arguments are, there is nothing stopping me from returning a string.</p><pre>const addValue = (a: number, b: number) =&gt; (a + b).toString();</pre><pre>console.log(addValue(2,3) + 100); // prints 5100</pre><p>We have decided to add the returned value from addValue which is ‘5’ to 100, the expected output should have been 105 but we got 5100, the reason is because our return value from the addValue is loose hence we can return any data type. To fix that:</p><pre>const addValue = (a: number, b: number):number =&gt; a + b;</pre><pre>console.log(addValue(2,3) + 100);</pre><p>The code above forces the arrow function to return a number data-type. Understanding this concept will help us grasp the remaining part of the article.</p><h3>Why do we need Generic</h3><p>In Java, generics are mostly used in Collections API to allow the client to specify the data type to be used.</p><blockquote>According to Wikipedia, Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.</blockquote><p>Let’s take a little example of a Typescript function.</p><pre>function doSomethingAndReturnExactType(a: number) : number {</pre><pre>    const stringify = JSON.stringify(a);</pre><pre>    return JSON.parse(stringify);</pre><pre>}</pre><p>This function takes a number as an argument and then returns a number. Ok, what is the problem with this simple function, can we call this function with a string? No, if we want to call it with a string, we have to create a different version with a string parameter and make it return a string like this:</p><pre>function doSomethingAndReturnExactType(a: string) : string {</pre><pre>   const stringify = JSON.stringify(a);</pre><pre>   return JSON.parse(stringify);</pre><pre>}</pre><p>Ok, what if we want to use an object, array e.t.c This is where Generics programming comes to the rescue. How do we solve this problem with Generics?</p><pre>function doSomethingAndReturnExactType&lt;T&gt;(a: T) : T {</pre><pre>    const stringify = JSON.stringify(a);</pre><pre>    return JSON.parse(stringify);</pre><pre>}</pre><p>What we have done is to basically declare a generic annotation with “&lt;T&gt;” and we replace all our statically typed data types with the generic annotation we have declared. You can see we have been able to decouple our function from any data type and we can call this function with any data type.</p><p>This example is not so useful but I hope it drives the concept home. The next example below is a stack data structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*sKEpXaP0JuFotU4u2DVXvQ.png" /></figure><p>Looking at the code, you can see that we use generic as the Array data type, Array&lt;number&gt;.</p><p>Note: This was what motivated me to write about it.</p><p>Let’s try to use the stack as a client</p><pre>const stack = new Stack();</pre><pre>stack.push(1);<br>stack.push(2);<br>console.log(stack.pop());</pre><p>The same problem arises, we can’t create a Stack with a string, array, object e.tc.</p><p>To solve this problem with Generics, we have to declare the class as a generic class, just like the Array example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*-oK4EiN_-8cN2oYTYoUzhg.png" /></figure><p>We have now declared our class with the generic &lt;T&gt; syntax, what that means is that we can declare the type we want to tie this class into.</p><p>And then notice that we are returning the same type in the pop and peek methods, in the push method, we are taking the same type as the argument to push.</p><p>Let’s use this as a client. We can still use this class as a loose class by using it as a normal javascript class without the strong type feature, Typescript lets us use that with the ‘any’ data-type.</p><pre>const stack = new Stack();</pre><pre>stack.push(1);</pre><pre>stack.push(&#39;Wale&#39;);</pre><p>The above example is loose, notice how I pass the number 1 in the first push operation, and then pass the string ‘Wale’ in the second push operation. If we want to be strict (we already saw the benefits in the previous section), we can use the strict Stack in two different ways:</p><p>The first way is to specify the data type when instantiating the Stack object as indicated below.</p><pre>const stack = new Stack&lt;number&gt;();<br>stack.push(1);</pre><pre>// stack.push(&#39;Waleola&#39;); // interpreter highlights this as an error</pre><p>The second way is to make the variable stack which is a reference to the instantiated object to be of type number</p><pre>const stack: Stack&lt;number&gt; = new Stack();</pre><pre>stack.push(1);</pre><pre>// stack.push(&#39;Waleola&#39;); // interpreter highlights this as an error</pre><h3>Conclusion</h3><p>Looking at the example code we have, you will notice that we get the interpreter to help us detect errors at runtime. The transpiler yells at us when there is a mismatch in our data-type binding. It is important to state that, typescript is built around javascript, hence loose code will run without any issue but you won’t get away with it when you work with compile languages like Java. The phrase “Monkey Work, Baboon chop”, actually this is a remixed version, the original version is “Monkey dey work, Baboon dey chop” is analogous to a person who does the dirty job in the background and then you get someone else taking credit for the work done; when we write generic code, the developer takes credit for it and none goes to the Typescript that is doing the dirty job under the hood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*Ll1-Qq90Rg2V10PCWPNERQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50e6f84bad6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker, it’s not rocket science, Build a Minified React App and Serve on Nginx — Part II]]></title>
            <link>https://medium.com/@spykins/docker-its-not-rocket-science-build-a-minified-react-app-and-serve-on-nginx-part-ii-ac251ea771ae?source=rss-4e8a96d870f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac251ea771ae</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[docker-image]]></category>
            <dc:creator><![CDATA[Waleola Akinsanmi]]></dc:creator>
            <pubDate>Sun, 12 Apr 2020 20:14:41 GMT</pubDate>
            <atom:updated>2020-04-12T20:14:41.182Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker, it’s not rocket science, Build a Minified React App and Serve on Nginx — Part II</h3><p>In <a href="https://medium.com/@spykins/docker-its-not-rocket-science-understanding-container-and-docker-cli-part-i-a74a1a535e8f">part 1</a> of this series, we learned about Docker Image and Container, in this series we will dive into how to create our own Docker image and how we can create an application and expose it through a port. We will primarily be looking at Dockerfile and how to specify commands in the Dockerfile.</p><p>In the first series, the first thing we did was to type ‘docker run hello-world’ and that printed “hello world” with some other information. What is in the hello-world image? If you are curious, please visit <a href="https://github.com/docker-library/hello-world">here</a>, to find out how it was created.</p><p>The Dockerfile of hello-world is like this</p><pre>FROM scratch<br>COPY hello /<br>CMD [&quot;/hello&quot;]</pre><p>We can see here that they are basically creating a Docker image from scratch, you must always have ‘FROM’ at the beginning of your Dockerfile. In our case, we will not start from scratch because we have awesome people who have created Docker image for almost everything we need in <a href="https://hub.docker.com/">Docker hub</a> and we can start building our own image ‘FROM’ the image they have created.</p><p>The second line “COPY” a binary file ‘hello’ from the same directory as the Dockerfile and copies it in the root folder of the container.</p><p>The third line CMD executes the binary file and it prints “hello world” and other information on the terminal.</p><h3>Ok, Let’s build our Own Hello world Image</h3><p>To build our first image, we need to create a Dockerfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*7sxd0qSgmw-DSr4-43oMgA.png" /></figure><p>I am currently in the docker-not-rocket-science folder, please ignore the ‘01-building-docker-image’, it is the git branch I am currently on, the README.md is also irrelevant.</p><p>The first thing is to create a Dockerfile:</p><pre>touch Dockerfile</pre><p>and add the code below in the Dockerfile.</p><pre>FROM ubuntu</pre><pre>CMD [&quot;/bin/echo&quot;, &quot;Hello world&quot;]</pre><p>To build our image we run this in the terminal</p><pre>docker build .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*sJG47kXYRpc7Y9u_G6OkOA.png" /></figure><p>To view the image generated</p><pre>docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*BYZccHyb_E1S-igCA060Jg.png" /></figure><p>The Docker image build was successful and we can see the image id generated in the terminal correlates with the one in the ‘docker images’, Note that we don’t have a tag and it doesn’t say the repository here. To run our new docker image:</p><pre>docker run --rm 860085349447</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*lQx2bbGwqW8xZ90uVwr3HQ.png" /></figure><p>We see that “Hello world” is printed out in the console.</p><p><strong>Running bash by default in Docker Image</strong></p><p>we can get our docker image to drop us in ubuntu bash by updating our Dockerfile to:</p><pre>FROM ubuntu</pre><pre>CMD [&quot;/bin/bash&quot;]</pre><p>and then we can build a new image by running</p><pre>docker build --tag my-docker-image .</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*gzzwk7znwJGtLVVisVkZVQ.png" /></figure><p>Now, we can see the new image is created with the tag we specified. To verify</p><pre>docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*2newiL5_RrM8lFA9uQgwXQ.png" /></figure><p>To interact with the new image created</p><pre>docker run -it --rm my-docker-image</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*84SGue25gSI-F7rIXvA2Hw.png" /></figure><p><strong>Ok Wale, I already know how to interact with images and containers from </strong><a href="https://medium.com/@spykins/docker-its-not-rocket-science-understanding-container-and-docker-cli-part-i-a74a1a535e8f"><strong>part 1</strong></a><strong> of the write-up, I wanna do something fun hun!</strong></p><p>Ok let’s figure out how we can bind our code in our system to a container, hahaha!!</p><p>Let’s create a src folder in our directory</p><pre>mkdir src<br>echo &quot;I am file a&quot; &gt; src/a.txt<br>echo &quot;I am file b&quot; &gt; src/b.txt<br>ls src</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*35G5HWprCtsYiBORryL73Q.png" /></figure><p>We have created this src folder where our code lives, now we want to bind the code to run in our ubuntu container.</p><pre>docker run -it --rm --mount type=bind,source=&quot;$(pwd)&quot;/src,target=/src my-docker-image</pre><p>The $(pwd) sub-command expands to the current working directory on Linux or macOS hosts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*oGO6nQjdaV0qWcFdQOHFlQ.png" /></figure><p>Note that we now have a ‘src’ folder in the root of our ubuntu machine, what we have done is to bind the ‘src’ folder in our project to the root directory of our container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*ZkBWs03pOSHKUyidLdPY5g.png" /></figure><p>Now, to confirm that our src folder in our computer is bounded to the container, we can tail the text file in the container and then make changes to it in our host machine</p><p>In the container, check for changes in the src/a.txt</p><pre>tail -f src/a.txt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*-zYGMvCx5VYRb_N1LTD01A.png" /></figure><p>Now, in my machine, if I change the text in src/a.txt, it will immediately sync with the docker container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*EEESDUyC4q3Fq2vGwRrsiQ.png" /></figure><p>The source code for this can be found <a href="https://github.com/spykins/docker-not-rocket-science/tree/01-building-docker-image">here</a>, to also check the difference between what we had in master and the first part, visit <a href="https://github.com/spykins/docker-not-rocket-science/pull/1/files">here</a>.</p><p><strong>Let’s switch gear a bit and run a simple Nodejs application in Docker.</strong></p><p>We will set up a simple Nodejs app, build it and run it in a Docker container. You can view the starting code <a href="https://github.com/spykins/docker-not-rocket-science/commit/75c53df5d1022e044e13330a65f80ac1a18a7a08">here</a>.</p><pre>“npm init -y”</pre><pre>npm install express</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*j3zK3MqQXNvarX-_g5uC2A.png" /></figure><p>This is the folder structure of the app I have bootstrapped. You can view the <a href="https://github.com/spykins/docker-not-rocket-science/commit/75c53df5d1022e044e13330a65f80ac1a18a7a08">hash commit</a> on Github.</p><p>Let’s talk about what we have in the folder</p><ul><li>“src/index.js”: This is where I am spinning up the express server. Please note that the express server will run at port 8080, and the host is “localhost” which we have denoted as “0.0.0.0” here.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pr77rYfv-u3Har2OWU7Y4A.png" /></figure><ul><li>“.dockerignore”:</li><li>“.gitignore”: The .dockerignore and .gitignore have the same content in this case. We are asking git and docker to ignore the files because we don’t want to push our node_modules to our repository and we definitely don’t want the risk of copying the node_modules in our host machine into the docker container node_modules.</li></ul><pre>node_modules</pre><pre>npm-debug.log</pre><ul><li>package.json: This has the information about our app and dependencies.</li><li>Dockerfile: The content of our Dockerfile has changed from ubuntu to node:10</li></ul><pre>FROM node:10</pre><p>We are starting our application with the official Nodejs image in Dockerhub. This image will already come preinstalled with Node and Npm. All we have to worry about is to install our app’s dependencies.</p><pre>FROM node:10</pre><pre>COPY package*.json ./</pre><p>The next stage is that, we are copying the package.json and package-lock.json from our host into the Docker image we are building.</p><pre>FROM node:10</pre><pre>COPY package*.json ./</pre><pre>RUN npm install</pre><p>The next thing we want to do is to install our dependencies on the Docker container. If we are running a production code, we should use `RUN npm ci — only=production`.</p><pre>FROM node:10</pre><pre>COPY package*.json ./</pre><pre>RUN npm install</pre><pre>COPY src src</pre><p>Now we are basically copying the src folder into the src folder of the machine. Usually, you will see “COPY . .” which means copy what is in the host machine work directory to the root of the docker container. Note that we already copied the package files, the only thing we need is to copy the src folder. You would ask why I added a “.dockerignore” if I am doing it manually, it’s just for learning purposes.</p><p>If you build your docker image at this point and run the container passing ‘bash’ as the CMD from the terminal, you will see that we have the package.json, package-lock.json file and our src folder.</p><pre>FROM node:10</pre><pre>COPY package*.json ./</pre><pre>RUN npm install</pre><pre>COPY src src</pre><pre>CMD [ &quot;node&quot;, &quot;src/index.js&quot; ]</pre><p>The next thing we want to do is to fire up the express server in src/index.js. Now it is time to build our image and run the container.</p><pre>docker build --tag my-first-node-app .</pre><p>To run the image</p><pre>docker run -it --rm --publish 3000:8080 my-first-node-app</pre><p>Now, we saw a new command line argument “ — publish”, note that we are running our Express server on port 8080, “ — publish” allows us to expose the Port in our container so we can access it on our host computer on port 3000. Now, we can visit “<a href="http://localhost:8080/">http://localhost:3000/</a>” to view our Nodejs app. Please visit <a href="https://github.com/spykins/docker-not-rocket-science/pull/2/files">here</a> to view the code changes</p><p>Note: “cntr+c” will not stop the running express server, to stop it, we will need to check the docker process and kill the process. For us to be able to kill the express server with “cntr+c”, pass init flag.</p><pre>docker run -it --init  --rm --publish 3000:8080 my-first-node-app</pre><blockquote>According to Docker, “You can use the — init flag to indicate that an init process should be used as the PID 1 in the container. Specifying an init process ensures the usual responsibilities of an init system, such as reaping zombie processes, are performed inside the created container”.</blockquote><p><strong>Understanding Multi-Stage Build by Building a Minified React app</strong></p><blockquote>We will use the multi-stage build approach to bootstrap our production ready minified application. According to <a href="https://docs.docker.com/develop/develop-images/multistage-build/">Docker</a>, With multi-stage builds, you use multiple FROM statements in your Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build. You can selectively copy artifacts from one stage to another, leaving behind everything you don’t want in the final image.</blockquote><p>The first thing we have to do is to bootstrap a React app, I will use the create-react-app.</p><blockquote>According to react <a href="https://reactjs.org/docs/create-a-new-react-app.html">documentation</a>, Create React App is a comfortable environment for learning React, and is the best way to start building a new single-page application in React. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production. You’ll need to have Node &gt;= 8.10 and npm &gt;= 5.6 on your machine. To set up your dev environmet, checkout out <a href="https://github.com/facebook/create-react-app#creating-an-app">github</a> and run:</blockquote><pre>npx create-react-app my-app<br>cd my-app<br>npm start</pre><p>In my case, I already have a working-directory initialized with git, I had to remove all the code in my directory and then create react app in my current directory. You can check the hash commit <a href="https://github.com/spykins/docker-not-rocket-science/commit/5c160ec018f8fcecb480180ef70590d09c3ba771">here</a>.</p><pre>npx create-react-app .<br>npm start<br></pre><p>NOTE: In order for us to understand how multi-stage build works, I have decided to use three stages:</p><ol><li>First stage: I will use node:12-stretch image to build a minified Nodejs app</li><li>Second stage: I will create another image from Ubuntu and copy the already minified code output from “first stage” into the container in the second stage</li><li>Third stage: I will create another image from Nginx container and we will copy the minified code in the folder to allow Nginx to run our app.</li></ol><p>You will notice from the step above that the second stage is redundant, I already have a minified code from the first stage and I can copy the minified code directly into the Nginx container. The reason I added the second stage is to allow us to dive a little into WORKDIR and also for us to know that container is nothing but some bunch of files in a folder as explained in <a href="https://medium.com/@spykins/docker-its-not-rocket-science-understanding-container-and-docker-cli-part-i-a74a1a535e8f">part 1</a> of the Docker series.</p><pre>FROM node:12-stretch AS FIRST_STAGE</pre><pre>WORKDIR /code/</pre><pre>COPY package*.json /code/</pre><pre>RUN npm ci --only=production</pre><pre>COPY . /code/</pre><pre>RUN npm run build</pre><p>NOTE: We name this stage “FIRST_STAGE” (you can call it whatever you want), we then copy our package.json, package-lock.json, install our dependency and then we build the minified version of our react app.</p><p>We have used WORKDIR to specify where we want docker to use as the directory.</p><p>At this point, we will try to build the app and then try to ensure the minified code is in the build folder.</p><pre>docker build --tag my-minified-react-app .</pre><pre>docker run -it --init --rm my-minified-react-app bash</pre><p>Now we can confirm that the minified code is in build “ls /code/build/”</p><p><strong>Second Stage</strong></p><p>Here, we will copy the minified code from the first stage build into an image we will build from Ubuntu.</p><pre>FROM node:12-stretch AS FIRST_STAGE</pre><pre>WORKDIR /code/</pre><pre>COPY package*.json /code/</pre><pre>RUN npm ci --only=production</pre><pre>COPY . /code/</pre><pre>RUN npm run build</pre><pre># stage two</pre><pre>FROM ubuntu:18.04 AS SECOND_STAGE</pre><pre>COPY --from=FIRST_STAGE /code/build /minified/</pre><p>NOTE: I have used Ubuntu in the second stage here because I want us to be able to run bash and ensure that our minified code has been copied from the first stage /code/build to our minified folder in stage two. In production, you want to use an <a href="https://hub.docker.com/_/alpine">alpine</a> container.</p><pre>docker build --tag my-minified-react-app .</pre><pre>docker run -it --rm my-minified-react-app bash</pre><p>Now we can confirm that the minified code is in our second stage “ls /minified/”</p><p>Third Stage</p><p>Now we want to copy the minified code from our second stage into the Nginx server so that Nginx can serve the app.</p><pre>FROM node:12-stretch AS FIRST_STAGE</pre><pre>WORKDIR /code/</pre><pre>COPY package*.json /code/</pre><pre>RUN npm ci --only=production</pre><pre>COPY . /code/</pre><pre>RUN npm run build</pre><pre># stage two</pre><pre>FROM ubuntu:18.04 AS SECOND_STAGE</pre><pre>COPY --from=FIRST_STAGE /code/build /minified/</pre><pre>#stage three</pre><pre>FROM nginx AS my_nginx</pre><pre>COPY --from=SECOND_STAGE /minified/ /usr/share/nginx/html</pre><p>To test this</p><pre>docker build --tag my-minified-react-app .</pre><pre>docker run -it --rm --publish 3000:80 my-minified-react-app</pre><pre># Now visit http://localhost:3000/</pre><h3>Conclusion</h3><p>It’s safe to say that Docker is just a bunch of files that have been jailed in a folder as described in the first part of this write-up. Please note that, in order to make this simple, <em>we execute all of the commands as the root user, this is to avoid changing ownership of folders and all the complexity that comes with it</em>. The next part of the write up will dive into how to manage users in Docker container, how to network containers, volumes and we will dive into Docker-Compose by creating a simple CRUD application with Nodejs, Mongo and React all running in containers.</p><p>Thanks for reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*p6K6FL6UzlRaiu7rbZiZEg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac251ea771ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker, it’s not rocket science — Understanding Container and Docker CLI — Part I]]></title>
            <link>https://medium.com/@spykins/docker-its-not-rocket-science-understanding-container-and-docker-cli-part-i-a74a1a535e8f?source=rss-4e8a96d870f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a74a1a535e8f</guid>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Waleola Akinsanmi]]></dc:creator>
            <pubDate>Sat, 04 Apr 2020 19:32:47 GMT</pubDate>
            <atom:updated>2020-04-14T22:28:05.944Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker, it’s not rocket science — Understanding Container and Docker CLI — Part I</h3><p>Everyone in the industry is talking about Docker and how it helps us set up a development environment effortlessly; ship quality software faster e.t.c.</p><p>In this series we will bootstrap a simple web application using React (You don’t need to know React) and we will build the production minified code and serve it on an Nginx server that we can access on the browser. We will also figure out how we can use Docker for our development environment; binding our source code to a volume.</p><p>We don’t need to take time to dive into virtualization or comparing it to containers. Please visit <a href="https://www.ibm.com/cloud/learn/containers">here</a> to learn more about virtualization. If you don’t have Docker already installed on your machine, visit <a href="https://www.docker.com/products/docker-desktop">here</a> to download the Docker Desktop.</p><p>After installation, you can run the command</p><pre><strong>docker run hello-world</strong></pre><p>You should see Hello from Docker! and it confirms that your installation is working.</p><p>Ok, what have we done? When we execute <em>docker run hello-world</em>, Docker checks its cache to find out if it has the image, since it doesn’t have it, it goes to docker hub (the repository, more like npm for Nodejs) and pulls down the image. What docker did is basically run &gt;&gt; <em>docker pull hello-world</em> and then execute &gt;&gt; <em>docker run hello-world. </em>Please note, I have been using “image” here.</p><p>After pulling down the image (hello-world), Docker executes the “run” command on the image to generate a container. To see what we have done, execute this:</p><pre><strong>docker images</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*B8CglOagFx2nJcOX5Zow8w.png" /></figure><p>Now, we see that we have an image, with repository “hello-world”, tag, image Id, date it was created and the size. That confirms the first point that docker ran hello-world and then pulled an image and saved it in our machine.</p><p>What about the container that was created? Ok run this</p><pre><strong>docker ps --all</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6k52t0VHJsWjZAnsjJrdg.png" /></figure><p>Now, we will see the container information. Container Id, the associated Image, the Command, data created, status ports, and the randomly generated name.</p><p>If we attempt to run the same command again.</p><pre><strong>docker run hello-world</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JOPO-1htjJTf0i75UCttMA.png" /></figure><p>This will create another container from the <em>cached</em> hello-world image; please note, an image. Also note that this time we are not pulling hello-world from docker hub. Docker is smart enough to use the cache version of the image that already exists.</p><h3>What is an Image, What is a Container?</h3><p>I will use the analogy of Object-Oriented Programming to describe it, I will describe an Image as a class definition, when you run the image(docker run image_name), you generate a container which I describe as creating an instance of the Image class. Every time you run it, you create an instance of the Image which is a new container.</p><p>Why do we keep creating a new container every time? The way I was able to understand this is to associate a container as a folder in your local machine, this folder is created with some Linux voodoo when you run an image.</p><h4>What is the Voodoo?</h4><p>The first voodoo it performs is basically using <strong>Chroot</strong> to make the created folder as the root of the container. Meaning when you are inside the container (which is just a folder in your machine), you can’t see any other folder in your machine, the root has been changed to your folder, cd ~/ inside the container will land you in the root of the container which is the folder that is being containerized or jailed; this folder has been jailed to a process in your machine. A prisoner in jail shouldn’t be allowed outside the prison.</p><p>Oh well, is jailing alone enough? someone in jail can still send coded messages to contact gang members outside to cause havoc if not properly checked. There is also another voodoo called n<strong>amespace</strong>, namespace basically just ensure someone from the jail can’t call someone outside, in Linux, it simply means we ensure that when you are in the container, you cannot see the process on the outside (the process of the host where the container(folder) resides). Now we have applied namespace to prevent the container from seeing other processes in the machine. That is perfect, although the container can still take up all the CPU and memory in the computer. Even though we have confined the prisoner to prison and we have also prevented the prisoner from sending coded messages to gang member, the guy can still cause havoc to inmates in prison.</p><p>The next Voodoo is called the <strong>control groups,</strong> now we want to control the resources (food, cigarette, bed space) this bad guy can access in prison. Control Group is a way to limit the resources (CPU, Memory e.t.c) the container can get access to in a container.</p><h4>Ok, I get you (Jailer), How do I remove the Container?</h4><p>There are two ways you can remove the container that already exists by</p><pre><strong>docker rm “Container Id”</strong></pre><pre><strong>docker rm “Name of the container”</strong></pre><p>You can ensure the container is being removed by using the previous command</p><pre><strong>docker ps  — all</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EZwDKSP83GZkgHlrcWvRxQ.png" /></figure><p>What if I want to run a docker image without keeping the container on my computer?</p><p>To do that, you can pass the rm command when running the image, docker will only create a temporary container and that will be cleared out immediately after the container finish executing</p><pre><strong>docker run --<em>rm</em> hello-world</strong></pre><p>You can execute &gt;&gt; “docker ps — all” to ensure that the container doesn’t stick around.</p><h4>Ok, how do I remove an image?</h4><p>There are two ways to also remove an image:</p><pre>docker image rm “REPOSITORY”</pre><pre>docker image rm “image id”</pre><p>Note: if you have a container that is using the image, you will need to remove all the containers and then run the code to remove the image. <em>You can’t remove a class definition when you have instances of the class all around the place</em>.</p><h4>What is the idea behind Container</h4><p>Containers are meant to be spun up and destroyed, they don’t last very long. If we need to save anything in a container, we need to mount it in a volume. When we run the container again, we can get the mounted information from the volume.</p><h4>Process State / Process Status</h4><blockquote>In a <a href="https://en.wikipedia.org/wiki/Computer_multitasking">multitasking</a> <a href="https://en.wikipedia.org/wiki/Computer">computer</a> system, <a href="https://en.wikipedia.org/wiki/Process_(computing)">processes</a> may occupy a variety of <a href="https://en.wikipedia.org/wiki/State_(computer_science)">states</a>. These distinct states may not be recognized as such by the <a href="https://en.wikipedia.org/wiki/Operating_system">operating system</a> <a href="https://en.wikipedia.org/wiki/Kernel_(computer_science)">kernel</a>. However, they are a useful abstraction for the understanding of processes. You can read more about process <a href="https://en.wikipedia.org/wiki/Process_state">here</a></blockquote><p>I use process state and process status interchangeably, You must have noticed we used</p><pre>docker ps --all</pre><p>We are checking the process state of docker, the ( — all) options allow us to see the processes that are not running.</p><pre>docker ps</pre><p>Will show us all running containers. This command is very important, this is where we can access the running container id and the name. Unfortunately, we can’t run docker ps, when we finish running docker run hello-world`, let’s play around with an Ubuntu image.</p><h4>Running Ubuntu in Container</h4><p>We understand from the previous section what a docker image is and we also pointed out a container is just a folder that is being jailed. Now we are going to pull Ubuntu from Docker hub, this will pull down the docker image from the docker hub (we used class declaration to explain above), every time we run the ubuntu image, we have a container (jailed folder) with a running ubuntu.</p><pre>docker pull ubuntu</pre><p>This will pull the latest ubuntu image on our machine, you can add tags to specify the version of ubuntu you want but we won’t go into that.</p><pre>docker images</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*3aiFhciMLSLEo2toBy4HBw.png" /></figure><p>This will display the images you have on your computer, you will see that we now have ubuntu image in our computer, sweet!.</p><h3>Understanding Docker CLI</h3><p>Now that we have pulled in the Ubuntu image into our machine, we need to run the image. Oh yeah! you guessed!</p><pre>docker run ubuntu</pre><p>You won’t see anything, the thing is, docker ran the image, generated a container and exited the container. Oh my, what is going on??? We already found that containers are meant to be run and disposed. To show that we ran a container</p><pre>docker ps --all</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*TNh6urXHCxC8FtkV90WqQA.png" /></figure><p>This will show a container created by ubuntu with status “Exited”, oh well, not too useful right? I know, so let’s run our docker image and print something out.</p><h4>CMD</h4><p>How do we now that we ran an Ubuntu Operating System? There is an idea of CMD, it is a command we want the container to execute after the container has been created from the image.</p><pre>docker run ubuntu ls -la</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*pqmuZdDoAwKqWA2dT8J4EQ.png" /></figure><p>We can see that Docker executes the command “ls -la” after creating the container from the Ubuntu image.</p><p>If that is not convincing enough, how about we list the CPU information in Ubuntu</p><pre>docker run ubuntu lscpu</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwGnUJikg7ed5vedQB2NKw.png" /></figure><p>Now we got the CPU information, which means we are running ubuntu in our container.</p><pre>docker ps</pre><p>This will not give us anything because we just instruct docker to create a container from the Ubuntu image and execute the CMD we passed into it.</p><pre>docker ps --all</pre><p>Will show us all the containers that was executed previously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CY6xghXYM6GewQQjnTuTTw.png" /></figure><p>Note: COMMAND session shows the command we passed when we were running the container. We will talk more about CMD when we are creating DockerFile in the next blog post.</p><h4>Please stop, how do I interact with the Ubuntu Machine created?</h4><p><strong><em>Interactive</em></strong></p><p>Well, you can do that with the ‘ — interactive’ flag.</p><pre>docker run --interactive ubuntu</pre><p>Which is the same as</p><pre>docker run -i ubuntu</pre><p>This will drop us into the Ubuntu bash, this is the same thing as typing <em>“docker run — interactive ubuntu bash” , </em><strong><em>bash</em></strong><em> is the CMD, we don’t need to specify the bash because the people that created Ubuntu image already specified bash as the default command when we don’t specify our own command, we simply override the default command with(“ls -la” and “</em>lscpu<em>” ) previously.</em></p><p><em>Now we can interact with the container through the bash</em>. To view the docker process status, we need to go to another terminal and type</p><pre>docker ps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*vGmpJN4Klm5MNiEWMQ5Zog.png" /></figure><p>Notice the status of the container is “Up”. We can kill the container by typing <em>“docker kill container_id|container_name”</em>.</p><pre>&gt;&gt; docker kill container_id</pre><ul><li>To kill the container</li></ul><pre>docker kill container_id</pre><h4>Pseudoterminal</h4><blockquote>According to <a href="https://en.wikipedia.org/wiki/Pseudoterminal">Wikipedia</a>, In some <a href="https://en.wikipedia.org/wiki/Operating_system">operating systems</a>, including <a href="https://en.wikipedia.org/wiki/Unix">Unix</a>, a <strong>pseudoterminal</strong>, <strong>pseudotty</strong>, or <strong>PTY</strong> is a pair of <a href="https://en.wikipedia.org/wiki/Pseudo-device">pseudo-devices</a>, one of which, the <em>slave</em>, emulates a hardware <a href="https://en.wikipedia.org/wiki/Text_terminal">text terminal</a> device, the other of which, the <em>master</em>, provides the means by which a terminal emulator <a href="https://en.wikipedia.org/wiki/Computer_process">process</a> controls the slave.</blockquote><p>To allocate pseudo-tty we pass -t as an argument (it’s just a terminal)</p><pre>docker run --interactive -t ubuntu</pre><p>This will land us into a terminal. Type “exit” to leave the container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*MB3XBNWMv_kGSwEJxwZ7dw.png" /></figure><h4>-it — name / — rm</h4><p>Now that we know how to interact with a running container in a pseudoterminal, we don’t need to type the “ — interactive” in full, we can just execute</p><pre>docker run -it ubuntu</pre><p>‘i’ represents interactive and the ‘t’ represents the terminal</p><p>— <strong>name</strong></p><p>Note that when we create a container, docker generates a random name, we can pass in the option to give it a name, the name of the container must be unique.</p><pre>docker run --name my-container ubuntu</pre><p>We can run</p><pre>docker ps --all</pre><p>To view the container created from ubuntu</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*22NVbEKDAZKZ7ADzhdFBcQ.png" /></figure><p>Note that the name of the container is my-container. The name must be unique for every container created, if we attempt to create another container with the same name, bad thing! happen.</p><pre>docker run --name my-container ubuntu</pre><p>This will throw an error,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qFsvuTMaz5zndNh0pGeqgQ.png" /></figure><p>to be able to run this again, we have to delete the already existing container.</p><pre>docker rm my-container</pre><p><strong>— rm</strong></p><p>We can use the “ — rm” flag to not save the container created when we run an image, so that we can reuse the name as many times as we want.</p><pre>docker run --name my-container --rm ubuntu</pre><p>You can go ahead and check the “docker ps — all” to see that the container is removed after we finish running it.</p><h4>— detach — attach — exec — dit</h4><p>In the previous subsection, we have been able to run a container, pass command-line options to interact with the container and get into a pseudo-terminal.</p><p><strong>— detach</strong></p><p>Detach will help us run a container and keep the process running without dropping us into the terminal</p><pre>docker run --detach -it --name my-container --rm ubuntu</pre><p>Running this, it will print the full id for the docker container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*gOh1iXwLbaYqYUzjC18PuA.png" /></figure><p>Running</p><pre>docker ps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*0hfZBrYgHQutPCbCxXtiCA.png" /></figure><p>We will see that our container is running, that is basically what detach does.</p><p>We can rewrite the command as</p><pre>docker run -dit --name my-container2 --rm ubuntu</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*dmtO1LqZvTPpzCxgYmUulA.png" /></figure><ul><li>-dit: ‘d’ stands for detach, ‘i’ for interactive and ‘t’ the terminal.</li></ul><p><strong>How do we get into the detached container?</strong></p><p>There are two ways to get into an already running container</p><ol><li>attach</li></ol><pre>docker attach ‘container_id’</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*2GDnvRXfkRe3xo9dUE8GUw.png" /></figure><p>In the screenshot, I attach into the first running container, I could as well type “docker attach my-container”. Notice that when I exited from the container, when I check the process state again, the first container is done.</p><p>2. exec</p><p>The exec lets us execute a command on the already running container.</p><pre>docker exec -it my-container2 bash</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*pSqXR3FLT4e1k2qd2fVnFg.png" /></figure><p>We already talked about this previously, ‘docker exec ‘ lets us run CMD on the running container, bash in this case.</p><pre>docker exec my-container ls -la</pre><p>Will list the files in the root directory of the ubuntu machine. <strong>Note that when we exit the container, our container is still running</strong>.</p><p>The next part of the series will decipher the DockerFile and we will create our own docker image (class definition) from pre-existing images on Docker hub.</p><p>In conclusion, The idea behind the container is that they are meant to be spun up and destroyed. I have tried to type the full name of all commands, there are always turns of shortcuts if you don’t like typing. For instance “docker image rm “image id” is the same as “docker rmi image_id”. As usual, there are lots of docker concepts like pausing, restarting, prune, commit e.t.c we didn’t get the chance to go into. Please visit <a href="https://docs.docker.com/engine/reference/commandline/cli/">Docker</a> documentation to learn more and visit <a href="https://medium.com/@spykins/docker-its-not-rocket-science-build-a-minified-react-app-and-serve-on-nginx-part-ii-ac251ea771ae">here</a> for the part II.</p><p>Thanks for reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*sBaUUaDmpmWS1gBq1tOxpg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a74a1a535e8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Async-Await, Generators And Symbols in Javascript Using Iterator Pattern — Part 1]]></title>
            <link>https://medium.com/@spykins/demystifying-async-await-generators-and-symbols-in-javascript-using-iterator-pattern-part-1-88b91a8d0ba7?source=rss-4e8a96d870f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b91a8d0ba7</guid>
            <category><![CDATA[javascript-object]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-oops]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[iterator-pattern]]></category>
            <dc:creator><![CDATA[Waleola Akinsanmi]]></dc:creator>
            <pubDate>Sat, 21 Mar 2020 18:15:18 GMT</pubDate>
            <atom:updated>2020-04-05T13:37:18.142Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying Async-Await, Generators, And Symbols in Javascript Using Iterator Pattern — Part 1</h3><p>Async-Await is a super version of Generators, while I consider Generators the super versions of Iterators, Iterators are built around the concept of Symbols. Iterators are a fancy paradigm built from a programming concept called iterable. An iterable is an object capable of returning its members one at a time, permitting it to be iterated over in a for-loop.</p><p>This post will dive deep into Symbols as Iterator, the next post will talk about Generators and we will see how Generators help us to write sweet and clean asynchronous code with Async-Await.</p><h3>Introduction to Symbol</h3><blockquote>According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol">MDN</a>, The Symbol() function returns a value of type symbol, has static properties that expose several members of built-in objects, has static methods that expose the global symbol registry, and resembles a built-in object class but is incomplete as a constructor because it does not support the syntax “new Symbol()”. Yak!!!! Feel free to read the documentation <a href="https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Symbol">here</a>.</blockquote><h3>How to create Symbols</h3><p>There are two ways to create Symbols</p><ol><li>Creating a Symbol without Reference: When you create a Symbol object like the snippet below, Symbol generates a unique identifier that you don’t have access to when you create it.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2FCX8V1F8orEZcNeX5S9hF%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2FCX8V1F8orEZcNeX5S9hF&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/84b137deb6e9608d0309e8928f31a89e/href">https://medium.com/media/84b137deb6e9608d0309e8928f31a89e/href</a></iframe><p>The output of the evaluation above is false irrespective of the fact that we pass the same string identifier into the Symbol constructor.</p><p>2. Creating Symbol With Reference: This is the best way to create a Symbol when we want to have the key to unlock the padlock created by Symbol.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2FFcqHsS6crD4reclULIqX%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2FFcqHsS6crD4reclULIqX&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3559fdd12ba8f52ca60434ff4613b5f/href">https://medium.com/media/a3559fdd12ba8f52ca60434ff4613b5f/href</a></iframe><p>The evaluation returns true because the two Symbols created with ‘Symbol.for’ function with the same string identifier returns the same unique identifier.</p><blockquote>According to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators">MDN</a> : In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. More specifically an iterator is any object which implements the Iterator protocol by having a next() method which returns an object with two properties: value, the next value in the sequence; and done, which is true if the last value in the sequence has already been consumed. If value is present alongside done, it is the iterator’s return value.</blockquote><blockquote>According to <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html">Oracle</a> : An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators differ from enumerations in two ways:</blockquote><blockquote>Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. Method names have been improved. This interface is a member of the Java Collections Framework.</blockquote><p>IMO, I think the Oracle definition does a little bit of justice to it. It still sounds super complicated though.</p><h3>Symbol.iterator</h3><p>‘Symbol.iterator’ is a classic example of Symbol built-in es6, you can learn more about it <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator">here</a>. There are lots of ways you can iterate over an array.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2Fef3tIoRI5zjKiYZeNnU9%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2Fef3tIoRI5zjKiYZeNnU9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/556aefec2bb52f3c69aa3d479617d43e/href">https://medium.com/media/556aefec2bb52f3c69aa3d479617d43e/href</a></iframe><p>The above snippet highlights some of the major ways you go through an array. Now we are going to attempt to loop through the same array using Symbol.iterator.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2Fge6FjPPJQp5buKMfAj6h%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2Fge6FjPPJQp5buKMfAj6h&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/adcb9d0ca5a833a296d96515680c98bc/href">https://medium.com/media/adcb9d0ca5a833a296d96515680c98bc/href</a></iframe><p>The output of the console is unsurprisingly a function. What’s heartbreaking is when you attempt to execute that function ‘<strong><em>numIterator()’</em></strong>, bad things happen. Although I can execute the function like this <strong><em>const “numIterator = nums[Symbol.iterator]();</em></strong> “<strong>.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2FW1sCSdTpxnqPC8fhKLYN%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2FW1sCSdTpxnqPC8fhKLYN&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fapi%2Fimage%2FW1sCSdTpxnqPC8fhKLYN&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/61e6711a241f3df42317b40e246086bd/href">https://medium.com/media/61e6711a241f3df42317b40e246086bd/href</a></iframe><p>The type of numIterator is an object. Let’s try to verify what this object contains. According to the oracle definition “It removes the element from the underlying collection during the iteration with <strong><em>well-defined semantics</em></strong>.”.</p><h4>Symbol.iterator next function</h4><p>We can call ‘next’ function on the object return from Symbol.iterator.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2F4wDApsHwikweqzkAnwMy%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F4wDApsHwikweqzkAnwMy&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b12de5c7a4e9f61309f55acef6819d3/href">https://medium.com/media/8b12de5c7a4e9f61309f55acef6819d3/href</a></iframe><p>Calling next returns an Object and we can call value on it to get the actual value. Note the done key is a boolean, this flags indicate when we have finished iterating over the collection.</p><p>You can use a while loop to go through an Iterator and then break out of the loop when done is true. Ideally, you want to use the Iterator for something like a LinkedList when constructing your graph data structure.</p><p>Let’s try to implement our own Iterator.</p><h3>Iterator Design Pattern in Javascript</h3><blockquote>According to <a href="https://en.wikipedia.org/wiki/Iterator_pattern">wikipedia</a>, In object-oriented programming, the <strong>iterator pattern</strong> is a design pattern in which an iterator is used to traverse a container and access the container’s elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.</blockquote><p>Let’s try to build a simple Iterator in Javascript.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2FRGC0hRtRRnuNOX3DF5io%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2FRGC0hRtRRnuNOX3DF5io&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2f67da57cbcd57483e2abbea0ae8145/href">https://medium.com/media/e2f67da57cbcd57483e2abbea0ae8145/href</a></iframe><p>Let’s use this code as the client and we can get more insight into what’s going on.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2FPvtgnqvXDgmhiPWBBwcX%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2FPvtgnqvXDgmhiPWBBwcX&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fapi%2Fimage%2FPvtgnqvXDgmhiPWBBwcX&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e68fd613e7422ab351e42ae9b728b338/href">https://medium.com/media/e68fd613e7422ab351e42ae9b728b338/href</a></iframe><p>We are passing our data source which is the array of numbers into the Iterator. I am returning an object when you call the function, note that the object has only one key, the key is a symbol. I chose to use Symbol because when we abstract this into a module, there is no way for the client to access the value in the Symbol unless the client knows the key. In this example, the key is declared in the function for simplicity sake, you can always wrap this function and generate a unique UUID every time or just allow the client to pass in their key depends on your use case.</p><p>This is the what I consider true abstraction in Javascript, we can truly make-instance variable truly private in Javascript. Let’s keep this as simple as possible.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2FxQ31ziq2ZLOqscW2RqJI%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2FxQ31ziq2ZLOqscW2RqJI&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fapi%2Fimage%2FxQ31ziq2ZLOqscW2RqJI&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/657ac660d414099d74139a1e2c28ae29/href">https://medium.com/media/657ac660d414099d74139a1e2c28ae29/href</a></iframe><p>From the object we returned previously, we are accessing the value in the key [Symbol.for(ITERATOR_KEY)]<strong><em>, </em></strong>This returns a function from the object. Note: <strong><em>[Symbol.for(ITERATOR_KEY)]()</em></strong> is the same as <strong>[Symbol.for(ITERATOR_KEY)]: function()</strong>. The reference key of the iterator points to a function.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2F4zMbcDkwTADbQ0kbpuDE%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F4zMbcDkwTADbQ0kbpuDE&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/179e76fc37bbbbd7cbc9474cf5dc5d0f/href">https://medium.com/media/179e76fc37bbbbd7cbc9474cf5dc5d0f/href</a></iframe><p>This is expected because when you execute the function, we return an object, please note the object { next: function()} declaration. Please note that we have a counter variable in the function and with the help of closure, our inner next function can access it, increment it and use it to check.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2Fox5ks9EaBKzbbAXsLZhM%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2Fox5ks9EaBKzbbAXsLZhM&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/37db6dceb89717501d91b29a71cc97fa/href">https://medium.com/media/37db6dceb89717501d91b29a71cc97fa/href</a></iframe><p>Note that we can call next on our Pointer and the next function will use counter current value to get the value from the Array and also set the done flag if the counter is greater than the length of the Array.</p><h3>Private Field using Symbols</h3><p>Using symbols, I think we can achieve true private instance variable that cannot be called from outside the class, I am not sure if there is a performance overhead. Imagine I am building a medical app and I want to have medical information of the patient</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2FUPzjPlay7TxrTrEs8wsJ%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2FUPzjPlay7TxrTrEs8wsJ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b3d38d0328036447f138db938180842/href">https://medium.com/media/3b3d38d0328036447f138db938180842/href</a></iframe><p>There are information that we probably want to make public and stuff we want to make private.</p><p>With Symbol, I can keep a constant of what I want to keep private in the file and then export the file.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%2FObDNBqV8OglGg6ISaoDC%3F&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2FObDNBqV8OglGg6ISaoDC&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/35e4948e25b7109c252fa4996700a79a/href">https://medium.com/media/35e4948e25b7109c252fa4996700a79a/href</a></iframe><p>Note that we are not using ‘Symbol.for(“key”)’ here, the reason is because we don’t want to get the same symbol when we instantiate with the same string. There is no way we can call ‘mriData’, ‘testResults’ on the Patient instance because we don’t know the Symbol unique identifier and there is no way we can get that also since we don’t have a key.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b91a8d0ba7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>