<?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 Ashan Dhananjaya on Medium]]></title>
        <description><![CDATA[Stories by Ashan Dhananjaya on Medium]]></description>
        <link>https://medium.com/@d7k?source=rss-dbc30324371e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*o9vNij6OjAMcDIMMS-PPCA.png</url>
            <title>Stories by Ashan Dhananjaya on Medium</title>
            <link>https://medium.com/@d7k?source=rss-dbc30324371e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:35:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@d7k/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[JavaScript TDZ and Variable Shadowing]]></title>
            <link>https://d7k.medium.com/javascript-tdz-and-variable-shadowing-db973010ef92?source=rss-dbc30324371e------2</link>
            <guid isPermaLink="false">https://medium.com/p/db973010ef92</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Ashan Dhananjaya]]></dc:creator>
            <pubDate>Sun, 08 Nov 2020 10:32:45 GMT</pubDate>
            <atom:updated>2020-11-08T10:32:45.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bxEkHw1xewxOFjmGunb-Cw.png" /></figure><p>In this article we will see how the<strong> <em>Temporal Dead Zone </em></strong><em>(</em><strong><em>TDZ</em></strong><em>)</em> and Variable Shadowing effects in our day to day programming life which introduced with the <strong>ES6</strong> in 2015. <strong><em>Temporal Dead Zone </em></strong><em>(</em><strong><em>TDZ</em></strong><em>)</em> affect our coding when we declare variables with let and the care that the developer needs to take. <strong>Variable shadowing</strong> occurs when a variable is declared in certain scope has the same name defined on it’s outer scope. And when we call the variable from the inner scope, the value mentioned in inner scope will be taken into account.</p><h3><strong><em>Temporal Dead Zone</em></strong></h3><h4>Declaration with var</h4><p>Let’s look at the following example that declares a variable through var:</p><pre><strong>function</strong> mainFunc() {<br>    alert(name);<br>    <strong>var</strong> name <strong>=</strong> &#39;Jorden&#39;;<br>}<br>mainFunc();</pre><p>As much as we have written code this way, when it is processed by a JavaScript engine it will be interpreted in this way:</p><pre><strong>function</strong> mainFunc() {<br>    <strong>var</strong> name;<br>    alert(name);<br>    name <strong>=</strong> &#39;Jorden&#39;;<br>}<br>mainFunc();</pre><p>What we have just seen is the <strong><em>hoisting</em></strong> (lifting) of the variable nameto the beginning of the code block in which it was declared. Though, we have the declaration var name;, which has no attribution. So it alert(name)displays it <em>undefined</em> instead of an error claiming that the variable does not exist.</p><p>However, when we use it let, introduced from <strong>ES2015</strong> (ES6) we need to be aware. Bearing in mind that variables declared with let have block scope and cannot be re-declared within the same scope.</p><h4>Let statements</h4><p>Variables declared as letare also <strong><em>hoisting</em></strong> (lifting). However, their access is only allowed after receiving an assignment; otherwise, we will have an error.</p><p>Let’s look at the previous example, this time using let:</p><pre><strong>function</strong> mainFunc() {<br>    alert(name);<br>    <strong>let</strong> name <strong>=</strong> &#39;Michael&#39;;<br>}</pre><pre>mainFunc();</pre><p>When we execute our code, we will receive the following error message:</p><pre>Uncaught ReferenceError: Cannot access &#39;name&#39; before initialization</pre><p>As stated, variables declared with let are also hoisted, so our code will look like this when interpreted:</p><pre><strong>function</strong> mainFunc() {<br>    <strong>let</strong> name;<br>    alert(name);<br>    name <strong>=</strong> &#39;Jackson&#39;;<br>}</pre><pre>mainFunc();</pre><p>But what explains this different behavior with variables declared with let? That&#39;s what we&#39;ll see next. Between the declaration of the variable with let and its assignment there is the <strong><em>Temporal Dead Zone (TDZ)</em></strong> . Any access made to the variable in that time will result in ReferenceError. However, it is a beneficial error, as accessing a variable before assigning it is rarely intentional in an application.</p><p>Nothing prevents us from deliberately doing this:</p><pre><strong>function</strong> mainFunc() {<br>    <strong>let</strong> name <strong>=</strong> <strong>undefined</strong>;<br>    alert(name); //TDZ<br>    name <strong>=</strong> &#39;Jackson&#39;;<br>}</pre><pre>mainFunc();</pre><p>The result of alert will be undefined. It makes perfect sense, because we access the variable name after receiving an assignment, that is, outside the <strong><em>Temporal Dead Zone</em></strong>.</p><blockquote>Variables declared with const are not affected by <strong>TDZ</strong>, as they must be initialized during their declaration.</blockquote><h3>Variable Shadowing</h3><h4>Global scope and Local Scope</h4><p>In JavaScript there are two types of scope. Lets check this example first,</p><pre>let firstName = &quot;Michael&quot;<br>function mainFunc() {<br>   let lastName = &quot;Jackson&quot;;<br>   console.log(lastName);<br>}<br>console.log(firstName); //Prints =&gt; Michael<br>mainFunc(); //Prints =&gt; Jackson</pre><ul><li>Local scope</li></ul><p>Variables defined <strong>within</strong> a function are <strong>local variables</strong>. So in the above example <strong>lastName</strong> is defined in the function so it is also a local variable .</p><ul><li>Global scope</li></ul><p>Variables defined <strong>outside</strong> a function are called <strong>global variables</strong>.Variable <strong>firstName</strong> declared in the out of the function <strong>mainFunc() </strong>so we identify it as a global variable.</p><h4>Shadowing</h4><p>Lets jump into the variable shadowing. Assume if we declare both the variables using the same variable name,</p><pre>let name = &quot;Michael&quot;<br>function mainFunc() {<br>   let name = &quot;Jackson&quot;;<br>   console.log(name); //Prints =&gt; Jackson<br>}<br>console.log(name); //Prints =&gt; Michael</pre><p>The variable declared in the local scope overrides the variable declared in the global scope this is why when we print the variable name inside the mainFunc() prints <strong>Jackson </strong>instead<strong> Michael </strong>this is variable shadowing. This helps to co-exist 2 variable with the same name variables, both be accessible but this not a good practice in programming.</p><h4>Why is it a problem?</h4><p>Since this condition has two consequences. Firstly, it blocks us from gaining access from the inner scope to the variable defined in the outer scope. Secondly, it prevents any changes or reassignments to the variable defined in the outer scope from within the inner scope. More importantly to remember though is that variable shadowing should be avoided. The reason is that it can obfuscate the intention and clarity of your program, which could potentially lead to hidden bugs and unintended results in programming.</p><h4>So how can I avoid it?</h4><p>Simply you can avoid variable <strong>shadowing</strong> by renaming these variables with a unique name such as firstName and lastName according to our example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db973010ef92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Avoid serializing dynamic JSON properties.]]></title>
            <link>https://d7k.medium.com/avoid-serializing-dynamic-json-properties-dfbcdc143ec9?source=rss-dbc30324371e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfbcdc143ec9</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Ashan Dhananjaya]]></dc:creator>
            <pubDate>Sun, 01 Nov 2020 15:53:56 GMT</pubDate>
            <atom:updated>2020-11-01T15:53:56.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dthqHwybcl7oNgZCmElQw.png" /></figure><h3>Problem domain</h3><p>There are several ways to add control <em>flags</em> to JavaScript objects. One is to modify the object directly:</p><pre><strong>const</strong> photo <strong>=</strong> {<br>    title: &#39;JavaScript Beginners&#39;,<br>    author: &#39;Mark Myers.&#39;<br>}<br>photo._key <strong>=</strong> 1;</pre><p>However, when we serialize the data to be sent to an API, the property _keywill be present:</p><pre><strong>const</strong> serializedPhoto <strong>=</strong> JSON.stringify(photo);<br>console.log(serializedPhoto);<br><em>/* <br>{<br>    title: &#39;JavaScript Beginners&#39;, <br>    author: &#39;Mark Myers.</em><em>&#39;<br>    _key: 1<br>}<br>*/</em></pre><p>This would not be a problem if the <strong>API</strong> followed the best practices of reading only the properties it expects to receive. But if the API does not follow this path, it is clear that we cannot send the property _key.</p><blockquote>Serializing <strong>JSON</strong> on disk on the Node.js platform would also be a problem, as the property would also be part of the serialized data.</blockquote><p>One solution is to delete the property added dynamically before serialization:</p><pre><strong>delete</strong> photo._key;<br><strong>const</strong> serializedPhoto <strong>=</strong> JSON.stringify(photo);<br><strong>delete</strong> serializedPhoto._key;<br>console.log(serializedPhoto);<br><em>/* <br>{<br>    title: &#39;JavaScript Beginners&#39;,<br>    author: &#39;Mark Myers.</em><em>&#39;<br>}<br>*/</em></pre><blockquote>The motivation for the post came from the problem faced by a colleague in his application made with Ionic 3. One of the libraries used by him directly modified the model associated with the component which ended up causing him problems in the architecture defined by him.</blockquote><p>The above example would not cause any major performance problems, but the scenario would be different if we had to iterate through a large list of objects to then delete the property _keyof each one. The good news is that there is another solution.</p><h3>Defining non-iterable properties</h3><p>A solution to the previous problem is to add the property to the object _keyas non-enumerable. A non-enumerable property will not be seen by repetition for...inor by the method Object.keys(). Since the function JSON.stringify()uses some iteration structure to construct the resulting JSON, non-enumerable properties will be ignored.</p><h3>A little about Object.defineProperty</h3><p>We create non-iterable properties with the aid of the function <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty">Object.defineProperty</a>. It receives as the first parameter the object we want to modify and as the second name of the property to be added. Finally, a descriptor object is passed as the last parameter. It is here that we indicate that the property is not enumerable through enumerable: false, including its value through value: 1:</p><p>Lets modify our code:</p><pre><strong>const</strong> photo <strong>=</strong> {<br>    title: &#39;JavaScript Beginners&#39;,<br>    author: &#39;Mark Myers.&#39;<br>}</pre><pre>Object.defineProperty(photo, &#39;_key&#39;, { <br>    enumerable: <strong>false</strong>, <br>    value: 1<br>});</pre><pre><strong>const</strong> serializedPhoto <strong>=</strong> JSON.stringify(photo);<br>console.log(serializedPhoto);<br><em>/* <br>{<br>    title: &#39;JavaScript Beginners&#39;,<br>    author: &#39;Mark Myers.</em><em>&#39; <br>}<br>*/</em></pre><p>The resulting JSON no longer contains the property _key. :)</p><h3>Conclusion</h3><p>We can dynamically add object to non-enumerable properties through Object.defineProperty. A consequence of these properties is that they will not be part of the JSON created through the function JSON.stringify.</p><p>The function Object.definePropertyallows you to define other characteristics of the dynamically added property. Is that you? Have you ever needed to use this function before? What problem did you try to solve? Leave your opinion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfbcdc143ec9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Babel 7: Configuration, Preset, and Plugin Usage]]></title>
            <link>https://d7k.medium.com/babel-7-configuration-preset-and-plugin-usage-b1ef675e2f2b?source=rss-dbc30324371e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1ef675e2f2b</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[plugins]]></category>
            <dc:creator><![CDATA[Ashan Dhananjaya]]></dc:creator>
            <pubDate>Mon, 02 Dec 2019 06:46:47 GMT</pubDate>
            <atom:updated>2019-12-02T06:46:47.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XmHUL5DeySv_dGmvbPqdDQ.png" /></figure><p>Often the developer wants to use the latest in JavaScript, but is frustrated by the lack of support in browsers or the Node.js platform. The good news is that we can generate compatible code through <a href="https://babeljs.io/">Babel</a> , the most widely used JavaScript compiler in the community. Babel version 7 is about to be released with several enhancements and new features, including support for the TypeScript language. In this article we learned how to configure it and use plugins to add features still proposed in the JavaScript language.</p><h3>Prerequisite</h3><p>To use Babel we need Node.js installed. We strongly recommend using the latest version (pair) available. This article used version 8.9.3. There are several ways to install Node.js, you can consult them at <a href="https://nodejs.org/en/">https://nodejs.org/en/</a> .</p><blockquote>Babel 7 no longer supports Node.js versions 0.10, 0.12 and 5.</blockquote><p>Now that we know which version of Node.js to use we can move on to the project structure.</p><h3>Project Structure</h3><p>Our next step will be to create the folder <strong><em>my-app</em></strong> and within it the subfolder app-src. This folder will contain all the files of the project, those that will be compiled by Babel. Let&#39;s enjoy and also create the file my-app/app-src/indedx.js:</p><pre>my-app<br>├── app-src<br>│   └── index.js</pre><p>Inside the folder my-appwe will create the file package.jsonby the command:</p><pre>npm init -y</pre><p>Excellent, we will have the following structure:</p><pre>my-app<br>├── app-src<br>│   └── index.js<br>└── package.json</pre><blockquote>For those who have never used Node.js, understand package.json as a various metadata holder for all modules used by the application, including scripts created by the developer to automate tasks .</blockquote><h3>Installing Babel 7</h3><p>One of the changes from version 6 to version 7 is the use of <strong>scoped packages</strong> .</p><blockquote>At the time of publication of this article, the version of Babel used was 7.7.4.</blockquote><p>We installed the modules coreand clithis way:</p><pre>npm install -S @babel/core @babel/cli</pre><p>O @babel/coreis the nerve center of the babel. Already @babel/cliis the command line client that allows us to interact with @babel/core.</p><h3>Calling babel-cli through a script</h3><p>Now that we have the dependencies downloaded, we need to create a script that calls us babel to target the folder app-src.</p><p>Let’s change my-app/package.json:</p><pre><em>// code before the script</em><br>  &quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>    &quot;build&quot;: &quot;babel app-src -d app --source-maps&quot;,<br>    &quot;watch&quot;: &quot;babel app-src -d app --source-maps --watch&quot;<br>  },<br><em>// code after the script</em></pre><p>Within the object assigned to the property we &quot;scripts&quot;add two more properties, a &quot;build&quot;and a &quot;watch&quot;.</p><p>The first script will compile all files within app-srceach time it runs, the second script will monitor the files in the folder in real time app-srcand, if any file is modified, will trigger the compilation process without having to worry about it. Regardless of the script called, the files resulting from the compilation process will be inside the folder my-app/app.</p><blockquote>The parameter --source-mapsis important as it will allow you to debug the generated script by pointing the error line in the original file and not in the compiled file.</blockquote><p>Let’s change the file my-app/app-src/index.jsand add a humble call to console.log:</p><pre><em>// my-app/app-src/index.js</em></pre><pre>console.log(&#39;I was compiled by Babel 7.&#39;);</pre><p>Now, inside the folder my-app, through our favorite terminal, let&#39;s run the script buildwith the command:</p><pre>npm run build</pre><p>The folder my-app/appwill be created and inside it we will have the index.jscompiled file :</p><pre>my-app<br>├── app &lt;-- folder generated by babel<br>│   └── index.js &lt;-- compiled file<br>├── app-src<br>│   └── index.js<br>└── package</pre><p>The command will result in the file my-app/app/index.js, identical to the original file in my-app/app-src/index.js. They are identical because we have not yet used any features that Babel offers us through <em>presets</em> or <em>plugins</em> , it is time to install them.</p><blockquote>When we use a compiler like Babel, it’s the generated scripts we load in our browser or our Node.js application, so we say the application depends on a build step.</blockquote><h3>@ babel / preset-env</h3><p>The first module we will install is @babel/preset-env. It is a special module that will compile our code for an earlier version of <strong><em>ECMASCRIPT</em></strong> if the feature we are using is not supported by market browsers.</p><p>Let’s install it:</p><pre>npm install -S @babel/preset-env</pre><p>It is not enough to install it, we need to configure Babel to take into account the module and we do it through the file my-app/.babelrc:</p><pre>// my-app/.babelrc<br><strong>{</strong><br>    &quot;presets&quot;: <strong>[</strong><br>      <strong>[</strong>&quot;@babel/preset-env&quot;, <strong>{</strong><br>        &quot;targets&quot;: <strong>{</strong><br>          &quot;browsers&quot;: <strong>[</strong>&quot;last 2 versions&quot;<strong>]</strong><br>        <strong>}</strong><br>      <strong>}]</strong><br>    <strong>]</strong>,<br><strong>}</strong></pre><blockquote>All presets prefixed with ES20xx have been discontinued, and @ babel / preset-env is required .</blockquote><p>The previous code adds @babel/preset-envas <em>preset</em> used by Babel by setting it at the same time. With this setting, only features not yet implemented in the last two versions of browsers will be <em>transcompiled</em> into compatible code.</p><blockquote>This preset is based on compatibility information posted at <a href="https://github.com/kangax/compat-table">https://github.com/kangax/compat-table</a></blockquote><p>Now that we have the preset set up, let’s take a leap into the future and use features that have been proposed to <em>TC39</em>, the committee that governs the future of the <strong><em>ECMASCRIPT</em></strong> specification.</p><h3>Installing plugins</h3><p>There are a number of plugins created exclusively for Babel. For testing purposes, we will install two of them that implement proposals that will still come into the language, they are:</p><ul><li><strong>@ babel / plugin-proposal-pipeline-operator</strong></li><li><strong>@ babel / plugin-proposal-optional-chaining</strong></li></ul><p>Let’s download both plugins at once:</p><pre>npm install -S @babel/plugin-proposal-pipeline-operator @babel/plugin-proposal-optional-chaining</pre><p>Downloading the plugins is not enough. They need to be added to the plugin list at .babelrc:</p><pre>// my-app/.babelrc<br><strong>{</strong><br>    &quot;presets&quot;: <strong>[</strong><br>      <strong>[</strong>&quot;@babel/preset-env&quot;, <strong>{</strong><br>        &quot;targets&quot;: <strong>{</strong><br>          &quot;browsers&quot;: <strong>[</strong>&quot;last 2 versions&quot;<strong>]</strong><br>        <strong>}</strong><br>      <strong>}]</strong><br>    <strong>]</strong>,<br>    &quot;plugins&quot;: <strong>[</strong><br>      &quot;@babel/plugin-proposal-pipeline-operator&quot;,<br>      &quot;@babel/plugin-proposal-optional-chaining&quot;<br>    <strong>]</strong>    <br><strong>}</strong></pre><p>Now that we have everything in place, we’ll take a look at the features offered by them.</p><h3>@ babel / plugin-proposal-pipeline-operator</h3><p>The pipeline operator is essentially a syntactic sugar for single-argument functions that are chained.</p><p>Let’s change by my-app/app-src/index.jsadding the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*UnX38EmGsI7_HtykAh4bAg.png" /></figure><p>After executing the command npm run buildthe file my-app/app/index.jswill have this structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*Cv16LKaZO3rYcG9UGBKPNQ.png" /></figure><p>Although structurally different from the original file, it is code that will work in current browsers and the Node.js platform.</p><h3>@ babel / plugin-proposal-optional-chaining</h3><p>We have the following code that accesses the property of an associated object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*dLmBOwCT_yafv-lhwddcqg.png" /></figure><p>Excellent, but if the property <strong>singer</strong> does not exist? We can shield you with the following trick:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*9jPboNn5q5jUeKK1bnEc_A.png" /></figure><p>However, using optional-chainingcan simplify our code to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*LyNqg1qQgtmJatgbFFnb0Q.png" /></figure><p>After compiling the file, the end result will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*IwLy0d6Y5NZ5PYincl9YFw.png" /></figure><h3>A note about Babel and TypeScript</h3><p>Although TypeScript may historically (when configured) compile code written in ES2015 (ES6) to ES5 and support some ES2017 (ES8) features such as <em>async / await</em> , its focus is not on compiling features under development or newly added in JavaScript specification that requires implementation in market browsers or the Node.js platform. In this sense, Babel is much freer to implement these features.</p><p>The good news is that from <a href="https://github.com/prettier/prettier/issues/2334">the TypeScript team’s own contribution to the Babylon parser</a> used by Babel and the preset <a href="https://www.npmjs.com/package/babel-preset-typescript">babel-preset-typescript</a> , it will be possible to use the full power of Babel with this language. Programmers in the TypeScript language can anticipate the future and use more modern JavaScript features.</p><h3>Conclusion</h3><p>With the help of Babel we can use the latest in JavaScript without having to wait for support to reach browsers or even the Node.js platform. Now, with the Babylon parser supporting TypeScript, programmers in this language will also be able to benefit from Babel.</p><p>Is that you? Already use Babel? Share your experience with us.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1ef675e2f2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS .includes() vs .some()]]></title>
            <link>https://d7k.medium.com/js-includes-vs-some-b3cd546a7bc3?source=rss-dbc30324371e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3cd546a7bc3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[methods]]></category>
            <dc:creator><![CDATA[Ashan Dhananjaya]]></dc:creator>
            <pubDate>Wed, 20 Nov 2019 09:26:01 GMT</pubDate>
            <atom:updated>2019-11-20T09:26:01.061Z</atom:updated>
            <content:encoded><![CDATA[<h3>JS .includes() vs .some()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQa8_ocRM5KmflbeR0Rurw.jpeg" /></figure><p>JavaScript <strong>array</strong> is a powerful data structure in web technologies. Methods such as .map(), .filter(), .includes(),and .reduce() helps a lot to overcome issues facing day to day <em>(</em><a href="https://medium.com/me/stats/post/af9908102a08"><em>Checkout my previous article on these 3 methods</em></a><em>)</em>. However, there are two similar but different methods that are part of your arsenal. In this article we will look in to the methods .includes()and .some()to differentiate them, to understand there different usages and applications.</p><h3>The problem domain</h3><p>We have a simple array of numbers. We need to check if the number 15 already exists in the list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*W3jz8ZX3bFhHBdRqpuUTbw.png" /></figure><p>Nothing exceptional here, except for the use of the <strong>ECMAScript</strong> <strong>5(ES5) </strong>that can be replaced by a for of/for in or a while loop. However, we can greatly simplify the code by using a feature introduced in <strong>ECMAScript</strong> <strong>7(ES7)</strong>.</p><h3>The .includes() method</h3><p>In ES7 the method has been introduced .includes(). Let&#39;s look at the previous code and then refactor it to use in the new function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*rVyZPe7j1aR8B9OPx_rTeg.png" /></figure><blockquote>Refactoring is altering the structure of code without changing its final behavior.</blockquote><p>The method .includes()returns true only if the element exists inside the array. Much leaner, yeah? But, this simplicity can lead to a developer error.</p><h3>Unexpected Result</h3><p>Let’s repeat the previous search example with .includes(), but this time searching an array of <strong>objects </strong>representing albums:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*kLAIUOn3mH9qDh4V0ALZMQ.png" /></figure><p>As much as the function .includes() worked in the previous example, it seems unable to find our album. What is the reason for this mischievous behavior?</p><h3>Comparisons between types</h3><p>Internally, it .includes() makes a comparison through ===. However, comparisons with ===or==only work as expected (compare value) with the types:</p><ul><li>Boolean</li><li>Null</li><li>Undefined</li><li>Number</li><li>String</li><li>Symbol (ES2015)</li></ul><p>When we compare variables that reference the type object, the interpreter will test whether they point to the same object in memory. Let&#39;s look at this simple example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*tFBeFfNJbH3n17yAHVw8sw.png" /></figure><p>However, the result will be true if we do something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*cTI9jfzScNPxvYGiMZ8tfQ.png" /></figure><p>In this context, we can .includes()return true as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*V7dOYxPzOkystaGdFT-68w.png" /></figure><p>As much as this solution works, it makes no sense to use it when searching for an object that we do not know its position, let alone if it exists. In this situation we can turn to the good old .some() ES5 method.</p><h3>Using the method .some()</h3><p>Let’s look at the previous example using the method .some():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*MFRzK_Vb7WbmenTaBk6iIQ.png" /></figure><p>The function .some() iterates through each an every element of the array by applying comparison logic. It will abort the iteration immediately as soon as it finds the first item that returns true during the comparison. The return will be true if there is any element that satisfies the logic .</p><p>The criterion used to compare the id of the object. Because the property stores a number, comparisons with ==or ===use the primitive value and not the reference.</p><p>We can still compare all properties of the object with the following trick:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*TzvV7ueN-7Y3qwY87jiC1g.png" /></figure><p>Through JSON.stringify converts the JavaScript object into a string that is nothing more than the textual representation of the object. Being a representation through one string, we can use ===or ==that the comparison will use the string representation.</p><p>One of the great advantages of .some() is being able to define a more refined comparison logic.</p><h3>Conclusion</h3><p>Modern features do not always solve everyday problems that developers face. It is important to know the <strong>problem</strong> and also the resource used to solve it so we have no surprises or mischievous behaviors as above.</p><p>Is that you? Have you ever been surprised by .includes()? Have you ever used it .some() to solve a problem? Leave your comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3cd546a7bc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 JavaScript things i did Wrong]]></title>
            <link>https://d7k.medium.com/4-javascript-things-i-did-wrong-7d57595e3d0f?source=rss-dbc30324371e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d57595e3d0f</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[methods]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ashan Dhananjaya]]></dc:creator>
            <pubDate>Mon, 18 Nov 2019 07:14:56 GMT</pubDate>
            <atom:updated>2019-11-18T13:45:33.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D87GXd6Tz48gAgbLUmTyLA.jpeg" /></figure><p>As software engineers when it comes to learning it never never ends. We have need to be updated with the trending all new technologies with the time. When it comes to <strong>Javascipt</strong> developments there was some hidden gems i never knew they were existing to make our lives easy without some struggles even though they are not big deals. From this article i will be explaining 5 of those hidden gems if you know more just leave a comment which will also help me.</p><h3>1. Three Dots …</h3><p>When you see three dots (…) in a code-base, it’s either spread operator or the rest parameters .</p><h3>Spread operator</h3><p>The Spread Operator <strong>expands</strong> an array into its elements. It can also be used for object literals. <strong>THREE DOTS </strong>allows for arrays and object literals to expand. Lets go thru below examples to get a more understanding,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*L3zmaTFWb9wzctCrJaqvhQ.png" /></figure><p>Without passing each key in the array to a function or to print as above. This is a quick and intuitive way to perform kind of action. When you clone a object you might using <strong><em>Object.assign().</em></strong> most of the time. The same operation can be also done for object literals by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*T23nkgG-fFjVzg5SCYAeVw.png" /><figcaption>Cloning object literals</figcaption></figure><p>You can also merge objects using spread operator like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*N7ZVR3wBOSh3xu72TTzdGQ.png" /><figcaption>Merge objects</figcaption></figure><h3><strong>Rest Parameters</strong></h3><p>Using rest parameters, we can combine any number of arguments into a single array and perform action on them. It has been introduced to reduce the boilerplate code that was induced by the arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*mSVKBInHCv4iMGsILnQ0Sw.png" /></figure><p>We can also use rest parameters to destruct arrays , that means that their data can be unpacked into individual variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*Wvv9BtfhQYMLyLsIcyhEJg.png" /><figcaption>Destruct arrays elements</figcaption></figure><h3>2. Includes() method</h3><p>Assume you have to search for a keyword/number exists in an array. What would you do? Just write an for-loop and a condition to check whether the string/number exists in the particular collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*wJQ1McQ9KHf93b1GXvbtUw.png" /></figure><p>In the above case you have to declare a variable outside the forloop as well. You can do the same buy a single line of code. Using<strong><em> .include()</em></strong> method. Keep in mind that it is case sensitive: if the item inside the collection is MAGOLINA, and you search for magolina, it will return false.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*PyboALuX4FRTT1Q1_kvDfg.png" /></figure><blockquote>It’s an intuitive approach to determine if a string or a number exists in an array</blockquote><h3>3. Some() method</h3><p>In a scenario like where you need to check whether few elements exists an array how you may do it now? Looping thru the array and checking one by one element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*fbw_rlS2GE49bpuD79k7Ug.png" /></figure><p>There is a pretty straightforward solution to do the same using the some()method checks if some elements exists in an array, and returns true or false. Inside the array we have negative and positive numbers, inside the arrow function we check whether ,Okay lets look in this example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*zbwhJeZYinyH0Y6teJHU3A.png" /></figure><p>This is somewhat similar to the concept of the includes() method, except the argument is a function and not a string or a number. I will write another article on comparing includes() vs some() comparing so you can have a better understanding of the behavior between them.</p><h3>4. Every() method</h3><p>The every() method loops through the all the elements available inside the array, checks every<strong> </strong>item, and returns true or false. Same as the some(). Except every item must satisfy the conditional statement, otherwise, it will return false. Before moving to the every lets try how we achieve such a scenario using a for loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*ra8SevHn5-qPE-Z5Jx3afQ.png" /></figure><p>Below example has one array contains both negative and positive values and the other only contains the negative values. The argument only checks for the negative numbers. So this only takes a single line of code if you use every() with an arrow function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*6w9oEWJLgPNw-Tn1vobIbA.png" /></figure><p>Hope you learned something from this. My next article will be on comparing <strong><em>.some()</em></strong> and <strong><em>.includes() </em></strong>methods. Let me know your comments and feedback. Keep in touch!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d57595e3d0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 JavaScript array manipulators]]></title>
            <link>https://d7k.medium.com/3-javascript-array-manipulators-af9908102a08?source=rss-dbc30324371e------2</link>
            <guid isPermaLink="false">https://medium.com/p/af9908102a08</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ashan Dhananjaya]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 09:25:48 GMT</pubDate>
            <atom:updated>2020-04-09T06:34:46.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*-wq4oLmikJJz5vqh5u9dlQ.jpeg" /></figure><p><strong>Javascript</strong>(JS) is a scripting languages, primarily used on the Web. As a developer who use <strong>Javascript, </strong>you may write several for loops daily-basis. Because if you require some sort of data collection (specially arrays in java script) modification, processing items in a collection are more common operation you will most likely encounter. Becoming familiar with these powerful methods will also help you to put your foundation as way to a pro <strong>Javascrtipt</strong> developer. Also if you are a developer just starting in <strong>JavaScript</strong>, maybe you haven’t heard of <strong>.filter(), </strong><strong>.map()</strong>, and <strong>.reduce().</strong> These three methods will reduce more than <strong><em>80%</em></strong> of the for loops you might write in your future code base.</p><p><em>Note that this article most likely applies to more programming language you might be using, as these are concepts that exist such as python.</em></p><h3>First Scenario : Filtering</h3><p>.filter()Yes as the word sounds this is what this method does, it filters an array based on any argument you provide. It is more likely the same as a map both return a new array. But,</p><blockquote><strong><em>.map()</em> returns a new array of elements where you have applied some function on the element so that it changes the original element (typically).</strong><strong><em>.filter()</em>returns a new array of the elements of the original array (with no change to the original values). </strong><strong><em>.filter()</em> will only return elements where the function you specify returns a value of true for each element passed to the function.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*Tk9XsyDlMCoUq-f9oPIpPw.png" /></figure><p>Okay lets write some code, here i’m going to filter the array and create a new array based on the number of characters i have for the name of each of the album,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*sC38oqHEni87EmeNk6Sogg.png" /></figure><p>If the number of character is more than 5 i filter them from the original array and return them. In es 6 you can do the same in one line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*auDUPiKF8xv4BH65ItGo_g.png" /></figure><h3>Second Scenario : Perform an action to every object</h3><p>Assume you have received an object array of audio albums. — each one representing an album. What you want to achieve at the end is a set of ids of album.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*l_YHaMnljfG0O12SgRLxHg.png" /></figure><p>As a developer you may imagine a set of solutions iterating through this array using <strong>for</strong> loops.</p><p>A <strong>.forEach()</strong> ?</p><p>Declare an empty array outside the <em>for-each</em> then iterate through the albums object array and push one by one id to the declared array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*2ZwLwtPtp6qWjJU8-1TlLQ.png" /></figure><p>A <strong>.for(...of)</strong> OR <strong>.for(...in) </strong>?</p><p>Declare an empty array outside the <em>for loop </em>then iterate through the albums object using <strong><em>of</em></strong> or <strong><em>in</em></strong> key word. Then push each id to the declared array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*lLyQOfy2ug2ICqJ-iKqGvg.png" /></figure><p>Just for() ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*V8Eo_AEXl6EW7-zqAu6EWQ.png" /></figure><p>All of the above solutions are all most the same. There maybe more ways than for loops as well in your mind (<strong>while or do/while</strong>). Just comment them out.</p><h4>Using .map</h4><p>You can achieve the same from a prototype map function like this.</p><blockquote>In es5</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*sMuppgvPFm7lTrxZQmXGWw.png" /></figure><blockquote>In es6</blockquote><p>You can simplify this more just using an arrow function like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*P0CSLcHetSWvCotLKBnn6w.png" /></figure><p>So it takes 2 arguments all over, a callback and an optional context (will be considered as context(<strong>this</strong>)in the callback) i haven’t used it in above example. This callback perform on <strong>each object in the array </strong>and <strong>returns each new value</strong> in the resulting array. Here you go another good example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*vx3Hy1f67BusvRVFn8IDYg.png" /><figcaption>ES5 Example</figcaption></figure><p>In the above example there is an array contains a list of number values. Using<em> </em><strong><em>.map</em></strong> we perform an action on each element inside the array and multiply it by 2. Below example is a simplified version using ES6,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*Yb0CteOlw4ShBZq7fSBcww.png" /><figcaption>ES6 Example</figcaption></figure><p>There are several mo advantages of the map as well, It lets you avoid making changes to the original array values plus you can also modify the array items individually.</p><h3>Third Scenario : Reduce the array into one single value</h3><p>Same as .map()we talked above, .reduce() also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other.</p><p>The accumulator can be pretty much anything (integer, string, object, etc.) and must be instantiated or passed when calling .reduce(). Let’s look in to the below example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*86zgBAbNUYDV3LGVqlCljg.png" /></figure><p>Assume you want to calculate the total price of the albums collection , if your trying to do it using a for loop you maybe doing it as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*6uZr6e584Lu7C9My4vVr4w.png" /></figure><p>But because of the advantage having an accumulator you do not have to maintain such a variable and do it straight forward like. So the accumulator holds the return which contains the sum. 0 is the initial value for the accumulator.</p><blockquote>In es5</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*TAaR5pnaQupWTkI0HGiSfA.png" /></figure><blockquote>In es6</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*LFC3UWEnsU7C1yORhK9sNQ.png" /></figure><p>Now assume you want to search for the most expensive album among, this is how easy it is,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*1SMzx7tsGIhW0mAL5uyYwA.png" /></figure><p>This callback compares the accumulator to each album’s price tag. If an album is pricier than the current accumulator pricey, then that value becomes the new pricey so that’s the one we return. In most of the cases the .reduce() is a pretty straight forward solution. You can also use the same in different scenarios such as identifying duplicates, group objects by property, execute promises sequentially etc.</p><h3>Lets combine all together</h3><p>Look at this object collection. Assume you have to filter the array based on a type of the album and then calculate the cost(<em>price+delivery cost</em>) and then you have the total price to calculate to deliver the albums.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*977yEwO5ZD5f9v-tHqluTQ.png" /></figure><p>Action to be taken,</p><blockquote>1.Filter based on the type of album <strong>.filter()</strong></blockquote><blockquote>2.Perform calculation on each of the object <strong>.map()</strong></blockquote><blockquote>3.Combine the cost and calculate the total <strong>.reduce()</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*93g-7GSc-P7eahyff2PpuQ.png" /></figure><p>Using ES6 you can simply this more like this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*fnMyNbr1ChXPujevn-EL9g.png" /></figure><p>Can you see the how powerful is these 3 methods on arrays? Hope you’ve learned something from this post Just share any thoughts on thee if you have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af9908102a08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get rid of GIT password]]></title>
            <link>https://d7k.medium.com/get-rid-of-git-password-60bbbcf4ed39?source=rss-dbc30324371e------2</link>
            <guid isPermaLink="false">https://medium.com/p/60bbbcf4ed39</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ashan Dhananjaya]]></dc:creator>
            <pubDate>Fri, 15 Nov 2019 07:47:37 GMT</pubDate>
            <atom:updated>2019-11-16T04:07:12.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8kHbmoApFoFXUu0bsRx_Q.jpeg" /></figure><h3>Can you dispose GIT password?</h3><p><strong>Yes you can</strong>. If you are a software engineer you may be dealing with any kind of a version controlling system at day to day work. Git is one of the most famous among the existing version controlling systems. If you are using terminal or command line to <strong>git </strong>version controlling you need to type your password all the time when you <strong>Push</strong>, <strong>Pull, Fetch </strong>etc. For this hesitation there is an existing reliable solution.</p><p>From this article i will describe you 3 simple steps, how to get rid of this hesitation.</p><ol><li>Generate a new private and public key pair.</li></ol><pre>$&gt; ssh-keygen -t rsa</pre><blockquote>If you already have one, just open ~/.ssh/id_rsa.pub (location depends on OS)</blockquote><pre>$&gt; cat ~/.ssh/id_rsa.pub</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*7wu3wZ41ha3mb_gyI7QgIA.jpeg" /><figcaption>Image 1</figcaption></figure><blockquote>Copy all the content of the key.</blockquote><p>2. Now go to your bit-bucket profile by : <a href="https://bitbucket.org/account/user">Click</a></p><p>Then go to settings-&gt;SSH-Keys. Then press Add key button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*htm8lRpp9IVzJ_pIKmUEKw.jpeg" /><figcaption>Image 2</figcaption></figure><p>3. SSH settings for repository</p><p>Now remember to use the “SSH” version before cloning. or If you’re already using HTTPS, just edit git/config then replace the URL in your repository which you need to access with SSH key.</p><pre>$&gt; vim .git/config</pre><p>Hope this help you. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60bbbcf4ed39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Task Scheduler to summarize MySQL database using an Enterprise service bus.]]></title>
            <link>https://d7k.medium.com/a-task-scheduler-to-summarize-mysql-database-using-an-enterprise-service-bus-1a8da123f868?source=rss-dbc30324371e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a8da123f868</guid>
            <category><![CDATA[stream-processing]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[esb]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Ashan Dhananjaya]]></dc:creator>
            <pubDate>Fri, 31 May 2019 04:00:09 GMT</pubDate>
            <atom:updated>2019-05-31T04:00:09.893Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OwAfw5rs7ahbSMSDMf03gQ.png" /></figure><p>There are tasks that we have to trigger based on time or intervals. Let me explain the problem i faced first: It is to summarize a MySQL table weekly basis to another table with some data(based on emails).This article will describe how to create a task scheduler which helped me to complete the challenge i faced. This scheduler based on an ESB will trigger once per week and filter the database. I have used the WSO2 Enterprise service bus(ESB) for the instance. (<strong>Note</strong> : <em>The whole article is presented on Ubuntu</em>)</p><p><strong>Prerequisites</strong>:</p><p>1. Enterprise service bus Latest (<a href="https://wso2.com/products/enterprise-service-bus/">WSO2 ESB Download</a>)</p><p>2. Maven</p><blockquote><em>sudo apt-get install maven</em></blockquote><p>3. Mysql</p><blockquote><em>sudo apt-get install mysql-server mysql-client</em></blockquote><p>4. Java 7 or latest</p><p><strong>The main steps for writing a task are as follows:</strong></p><p>1.Create the database and tables in the MySQL server.</p><p>2.Writing the EmailMoniterSumarizer Class.</p><p>3.Creating the pom.xml</p><p>4.Compile and bundle the Class.</p><p>5.Adding the compiled bundle to the ESB classpath.</p><p>6.Configure and schedule the Task.</p><p>The class EmailMoniterSumarizer will create the Database connection and summarize the data in the table into to a new table.</p><h3>Step 1. Create the database and tables in the MySQL server.</h3><p>You can use the following queries to create the database and the tables in MySQL.</p><blockquote>creating the database</blockquote><pre>CREATE DATABASE TestDB;</pre><blockquote>creating the table EmailMoniterMainTable</blockquote><pre>CREATE TABLE EmailMoniterMainTable(EmailCount INTEGER,Labels VARCHAR(255),Sender VARCHAR(255),Subject VARCHAR(255),TimeStamp INTEGER,ThreadID INTEGER);</pre><blockquote>creating the table GroupIndividualSum</blockquote><pre>CREATE TABLE GroupIndividualSum (DateCurrent VARCHAR(255),groupName VARCHAR(255),weekNo VARCHAR(255),mailCount INTEGER ,PRIMARY KEY (groupName,DateCurrent));</pre><h3>Step 2. Writing the EmailMoniterSumarizer Class.</h3><p>I recommend that you to start the project as a maven project. I have used eclipse developer studio.The EmailMoniterMainTable class implements org.apache.synapse.startup.Task. Each task should therefore implement the Task interface. This interface has a single execute() method. This method contains the code that is to be run at the specified intervals.</p><ul><li>Download the apache syanpase jar (<a href="http://www.java2s.com/Code/Jar/s/Downloadsynapsecore12jar.htm">Apache Syanpse Download</a>).</li><li>Download the MySQL Connector/J, which is the official JDBC driver for MySQL ( <a href="http://dev.mysql.com/downloads/connector/j/5.1.html">MySQL Connector Download</a> ).</li><li>Get Start with maven.(<a href="http://maven.apache.org/guides/getting-started/">Maven</a>)</li></ul><p><strong><em>Folder Directory for EmailMoniterSumarizer class :</em></strong></p><blockquote><em>&lt;projecthome&gt;/src/main/java/org/wso2/esb/test/EmailMoniterSumarizer.java</em></blockquote><p>The Complete implementation of the EmailMoniterSumarizer class is below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/963f3c9ab316f3813526fcfe466109bf/href">https://medium.com/media/963f3c9ab316f3813526fcfe466109bf/href</a></iframe><h3>Step 3. Creating the pom.xml</h3><p>If you create the project as a maven project you will find the pom.xml in the root folder of the project.Otherwise Create the file in the root folder.</p><p>We have to import all the external libraries we use for the project as dependencies to the pom.xml.</p><p>The pom.xml implementation is as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/878aa7a1a90b586819f59104671e104c/href">https://medium.com/media/878aa7a1a90b586819f59104671e104c/href</a></iframe><h3>Step 4. Compile and bundle the Class.</h3><p>Now You can do a mavan build using the command line. Just direct to your <em>&lt;ProjectHome&gt;</em> using command-line (where pom.xml exists) and maven install:</p><blockquote><em>mvn clean install</em></blockquote><h3>Step 5. Adding the compiled bundle to the ESB classpath.</h3><p>Then you can see a folder named “target” is created in your project home.Go in and copy the archive file and paste it into the following directory,</p><blockquote><em>&lt;WSO2ESB_HOME&gt;/repository/components/lib</em> directory.</blockquote><p><strong>Step 6.Configure and schedule the Task.</strong></p><p>1. Log in to the ESB console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*exr8s-ss1J2ooQWDTxfO_Q.png" /></figure><p>2. Click the “Main” button to access the “Manage” menu.</p><blockquote>First Click the Main Tab</blockquote><blockquote>Secondly Click the Scheduled task button in the manage group.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*UvLDdSt45R7vdCjpKcE9_g.png" /></figure><p>3. Click “ Add Task” .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*EBFr4UsmigVu7Myd_FQDgw.png" /></figure><p>4.The “<strong>New Scheduled Task</strong>” page will open. Enter a task name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*-dm2sZzkgGRTe6fMwxWvYA.png" /></figure><p>Enter “org.wso2.esb.tutorial.tasks.EmailMoniterSumarizer” as the Task Implementation.You can add the time you need to add as the interval time gap in seconds. I have added 5 seconds between 2 tasks.</p><p>After that Press the “Schedule” button to finish the task scheduling. Please leave a comment if anything helps to improve this experiance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a8da123f868" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to simply enable printing time-stamp in Gitblit logs.]]></title>
            <link>https://d7k.medium.com/how-to-simply-enable-printing-time-stamp-in-gitblit-logs-89934447ab28?source=rss-dbc30324371e------2</link>
            <guid isPermaLink="false">https://medium.com/p/89934447ab28</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[logger]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Ashan Dhananjaya]]></dc:creator>
            <pubDate>Thu, 30 May 2019 04:31:46 GMT</pubDate>
            <atom:updated>2019-05-30T04:31:46.916Z</atom:updated>
            <content:encoded><![CDATA[<p>Gitblit is a fully open source product. Uses pure Java stack for managing, viewing, and serving Git repositories.It mainly designed for small work groups to use as a tool to host a centralized repository.</p><p>I have done this for Gitblit 1.4 version. The default configuration doesn’t enable printing time-stamp in Gitblit logs to print we have to manually configure it. So using this blog i will describe how to achieve the task, manually configuring the Gitblit to print time-stamp. This is the time-stamp format which i’m going tho create <strong>[2014–11–18 16:35:24,045] INFO {com.gitblit.GitBlitServer}</strong>. You can change it as you prefer.</p><p><strong>Prerequisites:</strong></p><ol><li>Gitblit 1.4 version. (<a href="http://gitblit.com/">Download Latest</a>)</li><li>Java 7 or later version. (JRE or JDK any version works)</li><li>log4j.properties file. (<a href="https://github.com/gitblit/gitblit/blob/master/src/main/java/log4j.properties">GitHub File</a>)</li></ol><h3>Enabling time-stamp on the Console</h3><p>After unpacking the Gitblit you can run the shell script by this command in gitlib home directory.</p><blockquote><strong>./gitblit.sh</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*xu7y-4Qy-B3KaaQo0n49jw.png" /><figcaption>Git lab console view</figcaption></figure><p>First download the [1] GitHub file which i provided before and put it into the &lt;Gitblit_HOME&gt; directory. Now open the log4j.properties file. To add the pattern you prefer set the variable as follows,</p><blockquote><strong>ConversionPattern=[%d] %5p — %x %m %n</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*i_ly7E51CYku4wXxnzgGtQ.png" /><figcaption>This is the configuration to print the time-stamp in console.</figcaption></figure><p>Also %d can take a format pattern as in %d{dd MMM yyyy HH:mm:ss,SSS} you can pick and choose the elements that you want. When the format pattern is omitted the date will be in ISO8601 format. Now save it and close.<strong>You can find more conversion characters usage in log4j javadoc </strong>[<a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html">Example</a>]</p><h3>Configuring the JVM parameter.</h3><p>To enable the time-stamp you have to override Gliblit GO’s Log4j configuration. You can override it using gitblit.sh file in the home directory open it and comment all the stuff in it.Now copy and paste the below, command-line parameter configuration to the JVM into the “<strong>gitblit.sh</strong>” file.</p><blockquote><strong>java -Dlog4j.configuration=</strong>file:///home/&lt;user&gt;/Softwares/gitblit-1.4.0/log4j.properties<strong> -jar gitblit.jar — baseFolder data</strong></blockquote><p>In this parameter you have to set your default log4j.properties file path.You can not use override the default log4j configuration <em>AND</em> specify the — dailyLogFile parameter. Then you can Restart the Gitblit and you will see the console with the time-stamp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*cW86A54g8F861dlkZiTwMQ.png" /><figcaption>Console logs with enabled timestamps</figcaption></figure><p><strong>Enabling time-stamp in the log file.</strong></p><p>To do this First create a folder name <strong>logs</strong> which contains a file name <strong>gitblit.log</strong>. And now open the log4j.properties file and create a property name as FileWrite in the rootCategory element (you can use any variable name for this).</p><blockquote><strong>log4j.rootCategory=INFO, Console , FileWrite</strong></blockquote><p>Now you can configure the log4j.properties file to append the data into the file.And also you can set the file which you need to write the log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*u30y5r6W7u9RAmMD4OF0ww.png" /><figcaption>In the line 53 i have set the file which i need to write the data.</figcaption></figure><p>Now you can see after restarting the log has been written in to the gitblit.log file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RT9uGqJJExbZfELJuFWEpw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89934447ab28" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>