<?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 George Roubie on Medium]]></title>
        <description><![CDATA[Stories by George Roubie on Medium]]></description>
        <link>https://medium.com/@george-roubie?source=rss-b611ee7ec76e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VbTWeLwFhhb4NKtFvCQK1w.jpeg</url>
            <title>Stories by George Roubie on Medium</title>
            <link>https://medium.com/@george-roubie?source=rss-b611ee7ec76e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 23:46:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@george-roubie/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[All the JavaScript (ES6+)  Array methods  you need]]></title>
            <link>https://george-roubie.medium.com/all-the-javascript-es6-array-methods-you-need-a18c62578200?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a18c62578200</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 09:09:43 GMT</pubDate>
            <atom:updated>2021-07-16T14:20:51.109Z</atom:updated>
            <content:encoded><![CDATA[<h3>All the JavaScript (ES6+) Array methods you need</h3><p>I will explain to you with examples the methods: filter, map, reduce, find, findIndex, includes, some, every, flat and flatMap. Get ready because this article is huge, but it will be a reference for you in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*qG0su8GsQrXGJBFQ0j4zNA.png" /></figure><h3>filter</h3><p>One of the most common actions in an array is to filter it. With the filter, we can easily do it.</p><h4><strong>Example</strong></h4><blockquote>Save all female users to a separate array.</blockquote><p><strong>Without </strong><strong>filter:</strong></p><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const femaleUsers = [];<br>for (let i = 0; i &lt; users.length; i++) {<br>  if (users[i].gender === &#39;female&#39;) {<br>    femaleUsers.push(users[i]);<br>  }<br>}</pre><p><strong>With </strong><strong>filter:</strong></p><p>The filter gets as the first parameter a predicate function.</p><blockquote>A predicate function is a function that returns a boolean.</blockquote><p>This callback function has 3 parameters:</p><ol><li>The <strong>current element</strong> of the array (required)</li><li>The <strong>index</strong> of the current element in the array</li><li>The <strong>entire array</strong></li></ol><p>The filter <strong>creates a new array</strong> with all elements that satisfy the provided function.</p><pre>// Version 1</pre><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const findFemales = function(currentUser) {<br>  return currentUser.gender === &#39;female&#39;;<br>};<br>const femaleUsers = users.filter(findFemales);</pre><p>With <strong>destructuring</strong>, we can do it like this. If you don’t know what destructuring is, don’t worry read <a href="https://betterprogramming.pub/8-things-you-can-do-with-destructuring-in-javascript-3da9975fcec1">this</a>.</p><pre>// Version 2</pre><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const findFemales = function({ gender }) {<br>  return gender === &#39;female&#39;;<br>};<br>const femaleUsers = users.filter(findFemales);</pre><p>We can use the <strong>arrow function</strong> to simplify this.</p><pre>// Version 3</pre><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const findFemales = ({ gender }) =&gt; gender === &#39;female&#39;;<br>const femaleUsers = users.filter(findFemales);</pre><p>Now we can remove the function declaration and <strong>pass it directly</strong> into the filter.</p><pre>// Version 4</pre><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const femaleUsers = users.filter(<br>   ({ gender }) =&gt; gender === &#39;female&#39;<br>);</pre><p>I prefer version 3 so in this article, I will use the version 3 style.</p><h3>map</h3><p>Many times we need to manipulate the data of the array. With the map, we can easily do it.</p><h4><strong>Example</strong></h4><blockquote>Change the response data so that the male value of the gender to be M and the female value of the gender to be F. Also, change the property name to fullname.</blockquote><p><strong>Without </strong><strong>map:</strong></p><pre>const response = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const users = [];<br>for (let i = 0; i &lt; response.length; i++) {<br>  users.push({<br>    fullname: response[i].name,<br>    gender: response[i].gender === &#39;male&#39; ? &#39;M&#39; : &#39;F&#39;<br>  });<br>}</pre><p><strong>With </strong><strong>map:</strong></p><p>The map gets as the first parameter a callback function that returns a new item for the array. This callback function has 3 parameters:</p><ol><li>The <strong>current element</strong> of the array (required)</li><li>The <strong>index</strong> of the current element in the array</li><li>The <strong>entire array</strong></li></ol><p>The map <strong>creates a new array</strong> populated with the results of the provided function.</p><pre>const response = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const transformResponse = ({ name, gender }) =&gt; {<br>  return {<br>    fullname: name,<br>    gender: gender === &#39;male&#39; ? &#39;M&#39; : &#39;F&#39;<br>  }<br>};<br>const users = response.map(transformResponse);</pre><h3>reduce</h3><p>When we need to create a new value based on an array, reduce is very helpful.</p><h4><strong>Example 1</strong></h4><blockquote>Save the summary of the array items in a variable.</blockquote><p><strong>Without </strong><strong>reduce:</strong></p><pre>const numbers = [1,2,3,4,5,6,7,8,9];<br>let summary = 0;<br>for (let i = 0; i &lt; numbers.length; i++) {<br>  summary += numbers[i];<br>}</pre><p><strong>With </strong><strong>reduce:</strong></p><p>The reduce gets as the first parameter a callback function that returns a new item for the array. This callback function has 4 parameters:</p><ol><li>The <strong>accumulated value</strong> previously returned (required)</li><li>The <strong>current element</strong> of the array (required)</li><li>The <strong>index</strong> of the current element in the array</li><li>The <strong>entire array</strong></li></ol><p>The second parameter of the reduce is the <strong>initial value</strong>. If there is <strong>no initial value</strong> the <strong>first element</strong> in the array will be used <strong>as the initial value</strong> for the accumulator and the loop will begin from the second item on the array.</p><pre>const numbers = [1,2,3,4,5,6,7,8,9];<br>const addNumber = (acc, number) =&gt; {<br>  return acc + number;<br>}<br>const summary = numbers.reduce(addNumber);</pre><p>We didn’t pass an initial value because we wanted to use the first item of the array as the initial value.</p><h4><strong>Example 2</strong></h4><blockquote>Save the number of users that are female to a variable.</blockquote><p><strong>Without </strong><strong>reduce:</strong></p><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>let femaleUsersCount = 0;<br>for (let i = 0; i &lt; users.length; i++) {<br>  if (users[i].gender === &#39;female&#39;) {<br>    femaleUsersCount++;<br>  }<br>} </pre><p><strong>With </strong><strong>reduce:</strong></p><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const reduceFemaleCount = (acc, user) =&gt; {<br>  if (user.gender === &#39;female&#39;) {<br>    return acc + 1;<br>  }<br>  return acc;<br>};<br>const femaleUsersCount = users.reduce(reduceFemaleCount, 0);</pre><p>You must <strong>always return a value</strong> in the callback function, otherwise, you will <strong>lose the value of the accumulator</strong>. Rember that in every loop we return the new accumulated value.</p><p>Let’s make it a little better with destructuring.</p><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const reduceFemaleCount = (acc, { gender }) =&gt; {<br>  if (gender === &#39;female&#39;) {<br>    return acc + 1;<br>  }<br>  return acc;<br>};<br>const femaleUsersCount = users.reduce(reduceFemaleCount, 0);</pre><p>And one final optimization with the use of the ternary operator.</p><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const reduceFemaleCount = (acc, { gender }) =&gt; {<br>  return gender === &#39;female&#39; ? acc + 1 : acc;<br>};<br>const femaleUsersCount = users.reduce(reduceFemaleCount, 0);</pre><h4><strong>Example 3</strong></h4><blockquote>Change the response data so that the male value of the gender to be M. Also, change the property name to fullname. And save only the male users to a new array called maleUsers.</blockquote><p><strong>Without </strong><strong>reduce:</strong></p><pre>const response = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const transformResponse = ({ name, gender }) =&gt; {<br>  return {<br>    fullname: name,<br>    gender: gender === &#39;male&#39; ? &#39;M&#39; : &#39;F&#39;<br>  }<br>};<br>const findMales = function({ gender }) {<br>  return gender === &#39;M&#39;;<br>};<br>const users = response.map(transformResponse);<br>const maleUsers = users.filter(findMales);</pre><p>As you see we first changed the structure and the data with the map method and then we used the filter<strong> </strong>method to get the male users. In these cases, the reduce is a necessity.</p><p><strong>With </strong><strong>reduce:</strong></p><pre>const response = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const reduceMaleUsers = (acc, { name, gender }) =&gt; {<br>  if (gender === &#39;male&#39;) {<br>    return [...acc, { fullname: name, gender: &#39;M&#39; }];<br>  }<br>  return acc;<br>};<br>const maleUsers = response.reduce(reduceMaleUsers, []);</pre><p>As you know with the reduce we <strong>create a new single value</strong> but this value <strong>can be anything</strong>. Here we are creating a new array with only the male users and the data in the correct format. Filter and map together, super cool!</p><p>As the initial value, we used an empty array in order to fill it. If you don’t understand the ...acc , don’t worry read <a href="https://betterprogramming.pub/exploring-the-spread-operator-and-rest-parameter-in-javascript-8f425b4031e2">this</a>.</p><h3>find</h3><p>One of the most common actions in an array is to <strong>find</strong> an element inside an array. With the find, we can easily do it.</p><h4><strong>Example</strong></h4><blockquote>Find the user with id: 123, and save it to a variable.</blockquote><p><strong>Without </strong><strong>find:</strong></p><pre>const users = [<br>  { id: 123, name: &#39;George&#39; },<br>  { id: 456, name: &#39;Georgia&#39; }<br>];<br>let user;<br>for (let i = 0; i &lt; users.length; i++) {<br>  if (users[i].id === 123) {<br>    user = users[i];<br>    break;<br>  }<br>}</pre><p><strong>With </strong><strong>find:</strong></p><p>The find gets as the first parameter a predicate function. This callback function has 3 parameters:</p><ol><li>The <strong>current element</strong> of the array (required)</li><li>The <strong>index</strong> of the current element in the array</li><li>The <strong>entire array</strong></li></ol><p>The find <strong>returns</strong> the <strong>value</strong> of the <strong>first element</strong> in the array that satisfies the provided testing function.</p><pre>const users = [<br>  { id: 123, name: &#39;George&#39; },<br>  { id: 456, name: &#39;Georgia&#39; }<br>];<br>const findUser = ({ id }) =&gt; id === 123; <br>const user = users.find(findUser);</pre><p>Keep in mind that if <strong>no element</strong> of the array does not <strong>satisfy</strong> the provided testing function the find will <strong>return</strong> undefined.</p><h3>findIndex</h3><p>The method find will return undefined if it will <strong>not find the element</strong>. This is a problem in the case that it finds the element and the element has the value of undefined . In this case, you don’t know what actually happened.</p><p>So if you want to be sure if an element exists in an array and you don’t want its value use the findIndex.</p><h4><strong>Example</strong></h4><blockquote>Find the index of the user with id: 123, and save it to a variable.</blockquote><p><strong>Without </strong><strong>findIndex:</strong></p><pre>const users = [<br>  { id: 123, name: &#39;George&#39; },<br>  { id: 456, name: &#39;Georgia&#39; }<br>];<br>let userIndex = -1;<br>for (let i = 0; i &lt; users.length; i++) {<br>  if (users[i].id === 123) {<br>    userIndex = i;<br>    break;<br>  }<br>}</pre><p><strong>With </strong><strong>findIndex:</strong></p><p>The findIndex gets as the first parameter a predicate function. This callback function has 3 parameters:</p><ol><li>The <strong>current element</strong> of the array (required)</li><li>The <strong>index</strong> of the current element in the array</li><li>The <strong>entire array</strong></li></ol><p>The findIndex returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.</p><pre>const users = [<br>  { id: 123, name: &#39;George&#39; },<br>  { id: 456, name: &#39;Georgia&#39; }<br>];<br>const findUserIndex = ({ id }) =&gt; id === 123;<br>const userIndex = users.findIndex(findUserIndex);</pre><h3>includes</h3><p>When the <strong>array items</strong> are <strong>primitive types</strong> e.g. strings, numbers e.t.c. there is an easier way to<strong> find out if an element exists</strong> in an array with the includes.</p><h4>Example 1</h4><blockquote>Find if the number 9 is in the array.</blockquote><p><strong>Without </strong><strong>includes:</strong></p><pre>const numbers = [1,2,3,4,5,6,7,8,9];<br>const indexOf9 = numbers.indexOf(9);<br>if (indexOf9 !== -1) {<br>  console.log(&#39;9 exist&#39;);<br>} else {<br>  console.log(&#39;9 does not exist&#39;);<br>}</pre><p>The indexOf is the old way to find out if an element exists based on its position in the array. I actually never liked this approach because you have to check the -1 position, and it&#39;s not self-explained.</p><p><strong>With </strong><strong>includes:</strong></p><p>The includes gets as the first parameter the value to search for and returns true if it finds it, otherwise, it returns false.</p><pre>const numbers = [1,2,3,4,5,6,7,8,9];<br>if (numbers.includes(9)) {<br>  console.log(&#39;9 exist&#39;);<br>} else {<br>  console.log(&#39;9 does not exist&#39;);<br>}</pre><p>Now the code with the includes is <strong>self-explained</strong> and simpler to understand, even if you don’t know what includes do.</p><h4>Example 2</h4><blockquote>Find if a <em>NaN</em> is in the array.</blockquote><p><strong>Without </strong><strong>includes:</strong></p><pre>const numbers = [1,2,3,4,5,6,NaN,7,8,9];<br>const indexOfNaN = numbers.indexOf(NaN);<br>if (indexOfNaN !== -1) {<br>  console.log(&#39;NaN exist&#39;);<br>} else {<br>  console.log(&#39;NaN does not exist&#39;);<br>}</pre><p>Actually, <strong>this code</strong> <strong>does not work</strong> so the use of includes is required for the NaN.</p><p><strong>With </strong><strong>includes:</strong></p><pre>const numbers = [1,2,3,4,5,6,NaN,7,8,9];<br>if (numbers.includes(NaN)) {<br>  console.log(&#39;NaN exist&#39;);<br>} else {<br>  console.log(&#39;NaN does not exist&#39;);<br>}</pre><h3>some</h3><p>Many times we need to check if <strong>some elements</strong> in an array match a statement. With the some, we can easily do it.</p><h4><strong>Example</strong></h4><blockquote>Save to a boolean variable true if there is at least one male user.</blockquote><p><strong>Without </strong><strong>some:</strong></p><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>let hasMaleUsers = false;<br>for (let i = 0; i &lt; users.length; i++) {<br>  if (users[i].gender === &#39;male&#39;) {<br>    hasMaleUsers = true;<br>    break;<br>  }<br>}</pre><p><strong>With </strong><strong>some:</strong></p><p>The some gets as the first parameter a predicate function. This callback function has 3 parameters:</p><ol><li>The <strong>current element</strong> of the array (required)</li><li>The <strong>index</strong> of the current element in the array</li><li>The <strong>entire array</strong></li></ol><p>The some returns <strong>true</strong> if <strong>at least one element</strong> in the array <strong>satisfies</strong> the provided testing function, <strong>otherwise</strong>, it returns <strong>false</strong>.</p><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const isMale = ({ gender }) =&gt; gender === &#39;male&#39;;<br>const hasMaleUsers = users.some(isMale);</pre><h3>every</h3><p>Many times we need to check if <strong>every element</strong> in an array matches a statement. With the every, we can easily do it.</p><h4><strong>Example</strong></h4><blockquote>Save to a boolean variable true if all the users are females.</blockquote><p><strong>Without </strong><strong>every:</strong></p><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>let allFemales = true;<br>for (let i = 0; i &lt; users.length; i++) {<br>  if (users[i].gender !== &#39;female&#39;) {<br>    allFemales = false;<br>    break;<br>  }<br>}</pre><p><strong>With </strong><strong>every:</strong></p><p>The every gets as the first parameter a predicate function. This callback function has 3 parameters:</p><ol><li>The <strong>current element</strong> of the array (required)</li><li>The <strong>index</strong> of the current element in the array</li><li>The <strong>entire array</strong></li></ol><p>The every returns <strong>true</strong> if <strong>every element</strong> in an array <strong>satisfy</strong> the provided testing function, <strong>otherwise</strong>, it returns <strong>false</strong>.</p><pre>const users = [<br>  { name: &#39;George&#39;, gender: &#39;male&#39; },<br>  { name: &#39;Georgia&#39;, gender: &#39;female&#39; }<br>];<br>const isFemale = ({ gender }) =&gt; gender === &#39;female&#39;;<br>const allFemales = users.every(isFemale);</pre><blockquote><strong>Note:</strong> Calling every on an empty array will return true for any condition!</blockquote><h3>flat</h3><p>If you have an array that <strong>the</strong> <strong>elements of the array are arrays</strong> and you want to <strong>flatten</strong> this, you can do it with the flat method.</p><p>The flat gets only one parameter, the<strong> depth level</strong>. The depth level specifying how <strong>deep</strong> a nested array structure should be flattened. The parameter is not required because it has a default value of 1.</p><h4>Usage</h4><pre>const numbers = [1,2,3,[4,5],[[6,7]]];<br>console.log(numbers.flat());  // [1,2,3,4,5,[6,7]]<br>console.log(numbers.flat(1)); // [1,2,3,4,5,[6,7]]<br>console.log(numbers.flat(2)); // [1,2,3,4,5,6,7]</pre><blockquote>Tip: The bigger the depth level the slower will be the process.</blockquote><h3>flatMap</h3><p>The flatMap is the same as the map but it also does a flatting in the array of depth 1. You can’t change the depth level in the flatMap.</p><h4>Example 1</h4><blockquote>Flatten the array and change the value of each element to its square value.</blockquote><p><strong>Without </strong><strong>flatMap:</strong></p><pre>const numbers = [1,2,3,[4,5],[6,7]];<br>const flattedNumbers = numbers.flat();<br>const squareNumber = (n) =&gt; n * n; <br>const squaredNumbers = flattedNumbers.map(squareNumber);</pre><p><strong>With </strong><strong>flatMap:</strong></p><p>The flatMap gets as the first parameter a callback function that returns a new item for the array. <strong>If the item is an array it will be flattened.</strong></p><p>This callback function has 3 parameters:</p><ol><li>The <strong>current element</strong> of the array (required)</li><li>The <strong>index</strong> of the current element in the array</li><li>The <strong>entire array</strong></li></ol><p>The flatMap <strong>creates a new array</strong> populated with the results of the provided function.</p><pre>const numbers = [1,2,3,[4,5],[6,7]];<br>const squareNumber = (item) =&gt; {<br>  if (Array.isArray(item)) {<br>    return item.map((i) =&gt; i * i);<br>  }<br>  return item * item;<br>}; <br>const squaredNumbers = numbers.flatMap(squareNumber);</pre><p>We have to check if the item is an array because the 4th and the 5th item of the array are arrays and if you do array * array it will result NaN. That’s why when it’s an array, we change the value of its elements.</p><h4>Example 2</h4><blockquote>Flatten the array and change the value of each element to its square value. Calculate the square of numbers smaller than 6.</blockquote><p><strong>Without </strong><strong>flatMap:</strong></p><pre>const numbers = [1,2,3,[4,5],[6,7]];<br>const smallerThanSix = (n) =&gt; n &lt; 6;<br>const squareNumber = (n) =&gt; n * n; <br>const squaredNumbers = numbers<br>  .flat()<br>  .filter(smallerThanSix)<br>  .map(squareNumber);</pre><p><strong>With </strong><strong>flatMap:</strong></p><pre>const numbers = [1,2,3,[4,5],[6,7]];<br>const transformNumbers = (item) =&gt; {<br>  if (Array.isArray(item)) {<br>    return item.reduce((acc, i) =&gt; {<br>      if (i &lt; 6) {<br>        return [...acc, i * i];<br>      }<br>      return acc;<br>    }, []);<br>  } else if (item &lt; 6) {<br>    return item * item;<br>  }<br>  return [];<br>}<br>const squaredNumbers = numbers.flatMap(transformNumbers);</pre><p>The trick here is that if you <strong>return an empty array</strong> in the flatMap <strong>callback function</strong> you are <strong>not adding anything</strong> in the array. So you are doing the <strong>filtering</strong> of the array. Also here I have used reduce to do <strong>mapping</strong> and <strong>filtering</strong> in the array.</p><p>I am sure that if you understand all these ES6+ Array methods you will level up your code and maybe delete some third-party library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a18c62578200" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Things You Can Do With Destructuring in JavaScript]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/better-programming/8-things-you-can-do-with-destructuring-in-javascript-3da9975fcec1?source=rss-b611ee7ec76e------2"><img src="https://cdn-images-1.medium.com/max/2600/0*k8XsspwNEEA7rq3G" width="5607"></a></p><p class="medium-feed-snippet">Explore the destructuring assignment syntax</p><p class="medium-feed-link"><a href="https://medium.com/better-programming/8-things-you-can-do-with-destructuring-in-javascript-3da9975fcec1?source=rss-b611ee7ec76e------2">Continue reading on Better Programming »</a></p></div>]]></description>
            <link>https://medium.com/better-programming/8-things-you-can-do-with-destructuring-in-javascript-3da9975fcec1?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3da9975fcec1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 15:39:45 GMT</pubDate>
            <atom:updated>2022-03-10T11:34:52.997Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Exploring the Spread Operator and Rest Parameter in JavaScript]]></title>
            <link>https://medium.com/better-programming/exploring-the-spread-operator-and-rest-parameter-in-javascript-8f425b4031e2?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f425b4031e2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Tue, 13 Apr 2021 17:21:41 GMT</pubDate>
            <atom:updated>2021-04-30T22:12:24.789Z</atom:updated>
            <content:encoded><![CDATA[<h4>The spread operator has many use cases. Let’s go over a few of them</h4><figure><img alt="Hand reaching out toward the sky" src="https://cdn-images-1.medium.com/max/1024/0*dUWxgK1nC-YwG_gs" /><figcaption>Photo by <a href="https://unsplash.com/@drew_saurus?utm_source=medium&amp;utm_medium=referral">Drew Saurus</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a>.</figcaption></figure><p>In this article, I am going to explain what the<em> spread operator</em> and <em>rest parameter</em> are in JavaScript. But first, let’s see what a logical operator is in JavaScript.</p><h3>Logical Operators</h3><p>&amp;&amp; and ||<strong> </strong>are known as logical operators. The logical operators in JavaScript do not return only boolean like in other programming languages. The logical operators in JavaScript return a value. That’s why many developers call them select operators.</p><p>Rules:</p><ul><li>truthy &amp;&amp; whatever = whatever</li><li>falsy &amp;&amp; whatever = falsy</li><li>truthy || whatever = truthy</li><li>falsy || whatever = whatever</li></ul><p>But what are truthy and falsy? A value is truthy if you pass it in the Boolean constructor as an argument and it returns true. If it returns false, it is falsy.<br>A simpler rule is that the values false, null, undefined, 0, -0, ‘’, NaN, 0n, and -0n are falsy, while everything else is truthy.</p><pre>const user = null;<br>const currentUser = user || {};</pre><p>The example above is a simple way to add a default value. Because the user is null (falsy) the currentUser will be {}.</p><h3>Spread Operator</h3><p>The spread operator is an operator like +, -, /, etc. that takes an iterable (something that we can loop through) and expands it to individual elements. The syntax is three dots (...) and there are many use cases.</p><h4>Shallow copy an object</h4><p>Objects are non-primitive types that are saved by reference. If an object is equal to another object, when you change the first object, the second object is automatically changed.</p><pre>const user1 = { name: &#39;George&#39;, surname: &#39;ruby&#39; };<br>const user2 = user1;<br>user2.surname = &#39;Roubie&#39;;</pre><p>In the example above, the surname in user1 is also changed. We can use the spread operator to fix it.</p><pre>const user1 = { name: &#39;George&#39;, surname: &#39;ruby&#39; };<br>const user2 = { ...user1 };<br>user2.surname = &#39;Roubie&#39;;</pre><p>We can optimize the code above like this:</p><pre>const user1 = { name: &#39;George&#39;, surname: &#39;ruby&#39; };<br>const user2 = { ...user1, surname: &#39;Roubie&#39; };</pre><p>This code works because if you have the same key twice inside an object, the last one wins. This feature is very useful in state management techniques.</p><p>A shallow copy means that if there are nesting objects inside the copied object, the reference will remain.</p><pre>const roles = { isAdmin: true };<br>const user1 = { name: &#39;George&#39;, surname: &#39;Roubie&#39;, role: roles };<br>const user2 = { ...user1 };<br>user2.role.isAdmin = false;</pre><p>In the example above, the role is also changed in user1, so be careful.</p><h4>Combining objects</h4><p>With the spread operator, we can combine as many objects as we want to a new one.</p><pre>const userInfo = { name: &#39;George&#39;, surname: &#39;Roubie&#39; };<br>const userRoles = { roles: [&#39;admin&#39;, &#39;it&#39;] };<br>const token = { accessToken: &#39;123&#39;, refreshToken: &#39;456&#39; };<br>const currentUser = { ...userInfo, ...userRoles, ...token };</pre><h4>Conditionally add properties to an object</h4><p>You can easily add properties to an object with the help of the logical operator &amp;&amp; and the spread operator.</p><pre>const getRole = () =&gt; &#39;admin&#39;;<br>const user = { <br>  name: &#39;George&#39;, <br>  surname: &#39;Roubie&#39;,<br>  ...(getRole() === &#39;admin&#39; &amp;&amp; { admin: true })<br>};</pre><p>Because getRole() === &#39;admin&#39; returns true, &amp;&amp; returns { admin: true }. That’s why admin: true is added in the user object.</p><pre>const getRole = () =&gt; &#39;dev&#39;;<br>const user = {<br>  name: &#39;George&#39;,<br>  surname: &#39;Roubie&#39;,<br>  ...(getRole() === &#39;admin&#39; &amp;&amp; { admin: true })<br>};</pre><p>Now getRole() === &#39;admin&#39; returns false<strong> </strong>and &amp;&amp; returns false.<strong> </strong>But if you spread the false (e.g. { ...(false) }), the spread operator will return nothing ({}). That’s why nothing is added in the user object.</p><h4>Copying an array (shallow)</h4><p>Arrays are non-primitive types like objects. If an array is equal to another array, when you change the first array, the second array is automatically changed.</p><pre>const a = [1, 2, 3];<br>const b = [...a];<br>b.push(4);</pre><p>The code above can be also implemented with the slice method.</p><pre>const a = [1, 2, 3];<br>const b = [...a, 4];</pre><p>But with the slice method, we can’t add a value when we copying an array, as we did in the example above.</p><p>This copy is shallow, so if you have objects or arrays inside the array, the reference will remain.</p><pre>const data = { test: 1 };<br>const arr1 = [1, 2, 3, data];<br>const arr2 = [...arr1];<br>arr2[3].test = 3;</pre><p>In this example, arr1 and arr2 will have the value { test: 3 } in the third index of the array because the copy is shallow.</p><h4>Concatenating arrays</h4><p>With the spread operator, we can concatenate as many arrays as we want to a new one.</p><pre>const a = [1, 2, 3];<br>const b = [4, 5, 6];<br>const c = [7, 8, 9];<br>const d = [...a, ...b, ...c];</pre><p>If we want to concatenate two arrays, we can also do it with the concat method, but the concat method can only concatenate two arrays. With the spread operator, we can concatenate as many arrays as we want and we can also add values between the arrays, which we can’t do with the concat method.</p><pre>const a = [1, 2, 3];<br>const b = [5, 6, 7];<br>const c = [9, 10, 11];<br>const d = [0, ...a, 4, ...b, 8, ...c, 12];</pre><h4>Using an array as an argument</h4><p>Because the spread operator expands an array to individual elements, we can pass an array as an argument in a function. First, let’s see how we can do it without the spread operator.</p><pre>const userInfo = [&#39;George&#39;, &#39;Roubie&#39;];<br>const getUser = function(name, surname) {<br>  console.log(name, surname);<br>};<br>getUser(userInfo[0], userInfo[1]);</pre><p>With the spread operator, we can easily do it like this:</p><pre>const userInfo = [&#39;George&#39;, &#39;Roubie&#39;];<br>const getUser = function(name, surname) {<br>  console.log(name, surname);<br>};<br>getUser(...userInfo);</pre><p>This is very helpful when there are multiple arguments.</p><h3>Rest Parameter</h3><p>The syntax is the same as the spread operator’s, but it’s not an operator. In fact, it’s the exact opposite of the spread operator and combines the remaining elements into a single element.</p><pre>const user = function (name, age, ...hobbies) {<br>  console.log(name);<br>  console.log(age);<br>  console.log(hobbies);<br>}<br>user(&#39;George&#39;, 30, &#39;coding&#39;, &#39;killing zombies&#39;);</pre><p>The hobbies<strong> </strong>parameter is now an array with the value of [&#39;coding&#39;, &#39;killing zombies&#39;].</p><pre>var user = function (name, age, ...hobbies) {<br>  console.log(name);<br>  console.log(age);<br>  console.log(hobbies);<br>}<br>user(&#39;George&#39;, 30);</pre><p>When there are no values, the rest parameter makes hobbies an empty array. This is very helpful because we don’t have to worry when we don’t add extra values.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f425b4031e2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/exploring-the-spread-operator-and-rest-parameter-in-javascript-8f425b4031e2">Exploring the Spread Operator and Rest Parameter in JavaScript</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy Your Angular Application to GitHub Pages]]></title>
            <link>https://medium.com/better-programming/deploy-your-angular-application-to-github-pages-959dc04d9f10?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/959dc04d9f10</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Mon, 13 Jan 2020 19:36:56 GMT</pubDate>
            <atom:updated>2020-01-15T00:57:36.534Z</atom:updated>
            <content:encoded><![CDATA[<h4>Push that app live!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMKigK9Ft-bbW6zFBQ4hWA.png" /></figure><p>With <a href="https://pages.github.com/">GitHub Pages</a>, you can create a free website for your repository. It’s super easy and I will show you step-by-step how to deploy your Angular application to GitHub Pages.</p><p>First of all, you must create a new repository in GitHub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*tUOCT-kFrOrVBP3VYa1CFQ.png" /></figure><p>Now, go to the folder that you want to contain the project and execute:</p><pre>git clone repository-url</pre><p>Replace repository-url with the actual repository URL.</p><p>Now open the generated project folder with Visual Studio Code. Delete the Readme.MD file and commit it to check that the connection with GitHub works.</p><p>If everything works, open the terminal in Visual Studio Code (Ctrl + `) and execute:</p><pre>ng new appName --directory ./</pre><p>Replace appName with the application name.</p><p>Commit and push the generated files.</p><p>Next, in the package.json we must create a new npm script command.</p><pre>&quot;githubpage&quot;: &quot;ng build --outputPath=docs&quot;</pre><p>Save the package.json and execute:</p><pre>npm run githubpage</pre><p>This command will generate a docs folder. Commit and push the changes.</p><p>In the repository settings of the project in GitHub, in the GitHub Pages section, choose as the source: master branch/docs folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*Y7fZSd-kwdefdgE8K0LLZw.png" /></figure><p>When you choose this option, GitHub will refresh the page and will display the URL of the GitHub Page inside a light-blue alert. E.g.:</p><p>“Your site is ready to be published at <a href="https://georgeroubie.github.io/deploy-angular-application-to-githubpages/">https://georgeroubie.github.io/deploy-angular-application-to-githubpages/</a>.”</p><p>Copy only the URL and update the npm script command like this:</p><pre>&quot;githubpage&quot;: &quot;ng build --outputPath=docs --base-href=url-of-page&quot;</pre><p>Replace the url-of-page with the copied URL.</p><p>Execute:</p><pre>npm run githubpage</pre><p>Commit and push the changes to see your GitHub Page work.</p><p>Normally, it needs two to three minutes before you see the changes.</p><h3>Resources</h3><p>The code for this piece can be found on <a href="https://github.com/georgeroubie/deploy-angular-application-to-githubpages">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=959dc04d9f10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/deploy-your-angular-application-to-github-pages-959dc04d9f10">Deploy Your Angular Application to GitHub Pages</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make API Calls the Right Way in Angular]]></title>
            <link>https://medium.com/better-programming/angular-api-calls-the-right-way-264198bf2c64?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/264198bf2c64</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 12:35:14 GMT</pubDate>
            <atom:updated>2020-08-20T07:46:26.195Z</atom:updated>
            <content:encoded><![CDATA[<h4>Best practices for making your API calls</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Km9KJLOwXYMl6xmIZbVQ-Q.png" /></figure><p>If you’re creating an Angular application, one of the things you’ll need to do is make an API call. I’ll show you how to do it the right way, avoiding bugs or repeating yourself and making it easier to upgrade to a new version of Angular.</p><p>A common mistake of an API call inside a component is this:</p><pre>this.httpClient.get(&#39;https://www.domain.com/api/data/&#39; + this.id);</pre><p>This is wrong for three reasons:</p><ol><li>You’re using the API URL directly in the component, and if you need to change the API URL, you must change it in every component.</li><li>You’re using Angular’s httpClient<em> </em>directly in the component, and if Angular replaces this module with another module, you must change it in every component.</li><li>The path variable is not encoded. So if a character isn’t a valid URL character, the API call will fail.</li></ol><p>First of all, you must know what a CoreModule<em> </em>and a SharedModule are. If you don’t know, please read <a href="https://levelup.gitconnected.com/where-shall-i-put-that-core-vs-shared-module-in-angular-5fdad16fcecc">this</a>.</p><h3>Getting Started</h3><p>Inside src/app, create a folder called config with a constants.ts file inside.</p><pre>// Angular Modules<br>import { Injectable } from &#39;@angular/core&#39;;</pre><pre>@Injectable()<br>export class Constants {<br>    public readonly API_ENDPOINT: string = &#39;domain/api&#39;;<br>    public readonly API_MOCK_ENDPOINT: string = &#39;mock-domain/api&#39;;<br>}</pre><p>Import this file into the CoreModule.</p><p>We have two variables: one for the actual API endpoint and one for mock — but why?</p><p>Most of the time, the API models are completed but the actual call isn’t implemented. To not wait for an API call to be implemented, you can create a dummy call from, for example, JsonGenerator and use this in your application.</p><p>Now if the domain of the API is changed, you only need to change the above file and you’re ready.</p><h3>Create an api-http.service.ts File</h3><p>Inside src/app/core/services, create an api-http.service.ts file.</p><pre>// Angular Modules<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;</pre><pre>@Injectable()<br>export class ApiHttpService {</pre><pre>  constructor(<br>    // Angular Modules<br>    private http: HttpClient<br>  ) { }</pre><pre>  public get(url: string, options?: any) {<br>    return this.http.get(url, options);<br>  }</pre><pre>  public post(url: string, data: any, options?: any) {<br>    return this.http.post(url, data, options);<br>  }</pre><pre>  public put(url: string, data: any, options?: any) {<br>    return this.http.put(url, data, options);<br>  }</pre><pre>  public delete(url: string, options?: any) {<br>    return this.http.delete(url, options);<br>  }<br>}</pre><p>Import this file into the CoreModule.</p><p>In Angular 4.3, the HttpModule<em> </em>became legacy, and the new HttpClientModule<em> </em>became the default module for making API calls. If something like this happens again, you won’t need to change the use of the module in every component but only in this file. The upgrade will be easier.</p><h3>Creating the Other Requisite Files</h3><p>Inside src/app/shared/classes, create a query-string-parameters.ts file.</p><pre>export class QueryStringParameters {<br>  private paramsAndValues: string[];</pre><pre>  constructor() {<br>    this.paramsAndValues = [];<br>  }</pre><pre>  public push(key: string, value: Object): void {<br>    value = encodeURIComponent(value.toString());<br>    this.paramsAndValues.push([key, value].join(&#39;=&#39;));<br>  }</pre><pre>  public toString = (): string =&gt; this.paramsAndValues.join(&#39;&amp;&#39;);<br>}</pre><p>This class gets a query string key-value set and encodes the value. It also returns all the query string key-value sets in a string with the &amp; character: <br>e.g., id=3&amp;type=customer.</p><p>Inside src/app/shared/classes, create an url-builder.ts file.</p><pre>// Application Classes<br>import { QueryStringParameters } from &#39;./query-string-parameters&#39;;</pre><pre>export class UrlBuilder {<br>  public url: string;<br>  public queryString: QueryStringParameters;</pre><pre>  constructor(<br>    private baseUrl: string,<br>    private action: string,<br>    queryString?: QueryStringParameters<br>  ) {<br>    this.url = [baseUrl, action].join(&#39;/&#39;);<br>    this.queryString = queryString || new QueryStringParameters();<br>  }</pre><pre>  public toString(): string {<br>    const qs: string = this.queryString ?<br>                       this.queryString.toString() : &#39;&#39;;<br>    return qs ? `${this.url}?${qs}` : this.url;<br>  }<br>}</pre><p>This class uses the QueryStringParameters class to generate the final API URL:<br>e.g., <a href="https://domain.com/api/get-user?id=3&amp;type=customer">https://domain.com/api/get-user?id=3&amp;type=customer</a>.</p><p>The above URL is a combination of three parts:</p><ol><li>Base URL: <a href="https://domain.com/api">https://domain.com/api</a></li><li>Action: get-users</li><li>Query strings: id=3&amp;type=customer</li></ol><p>The URL builder takes these things as parameters to create the final API URL.</p><p>Inside src/app/core/services, create an api-endpoints.service.ts file.</p><pre>// Angular Modules<br>import { Injectable } from &#39;@angular/core&#39;;<br>// Application Classes<br>import { UrlBuilder } from &#39;../../shared/classes/url-builder&#39;;<br>import { QueryStringParameters } from &#39;../../shared/classes/query-string-parameters&#39;;<br>// Application Constants<br>import { Constants } from &#39;src/app/config/constants&#39;;</pre><pre>@Injectable()<br>export class ApiEndpointsService {</pre><pre>  constructor(<br>    // Application Constants<br>    private constants: Constants<br>  ) { }</pre><pre>  /* #region URL CREATOR */<br>  // URL<br>  private createUrl(<br>    action: string, <br>    isMockAPI: boolean = false<br>  ): string {<br>    const urlBuilder: UrlBuilder = new UrlBuilder(<br>      isMockAPI ? this.constants.API_MOCK_ENDPOINT :   <br>      this.constants.API_ENDPOINT,<br>      action<br>    );<br>    return urlBuilder.toString();<br>  }</pre><pre>  // URL WITH QUERY PARAMS<br>  private createUrlWithQueryParameters(<br>    action: string, <br>    queryStringHandler?: <br>      (queryStringParameters: QueryStringParameters) =&gt; void<br>  ): string {<br>    const urlBuilder: UrlBuilder = new UrlBuilder(<br>      this.constants.API_ENDPOINT, <br>      action<br>    );<br>    // Push extra query string params<br>    if (queryStringHandler) {<br>      queryStringHandler(urlBuilder.queryString);<br>    }<br>    return urlBuilder.toString();<br>  }<br>  <br>  // URL WITH PATH VARIABLES<br>  private createUrlWithPathVariables(<br>    action: string, <br>    pathVariables: any[] = []<br>  ): string {<br>    let encodedPathVariablesUrl: string = &#39;&#39;;<br>    // Push extra path variables<br>    for (const pathVariable of pathVariables) {<br>      if (pathVariable !== null) {<br>        encodedPathVariablesUrl +=<br>          `/${encodeURIComponent(pathVariable.toString())}`;<br>      }<br>    }<br>    const urlBuilder: UrlBuilder = new UrlBuilder(<br>      this.constants.API_ENDPOINT,  <br>      `${action}${encodedPathVariablesUrl}`<br>    );<br>    return urlBuilder.toString();<br>  }<br>  /* #endregion */<br>}</pre><p>Import this file in the CoreModule.</p><p>This service can:</p><ol><li>Create an API URL that uses the real or the mock API.</li><li>Create an API URL with query strings.</li><li>Create an API URL with path variables.</li></ol><p>All the API URLs will be provided from this service. Let’s create some URLs inside the service.</p><pre>public getNewsEndpoint(): string {<br>  return this.createUrl(&#39;news&#39;);<br>}</pre><p>This method will return: <br>https://domain.com/api/news</p><pre>public getNewsEndpoint(): string {<br>  return this.createUrl(&#39;news&#39;, true);<br>}</pre><p>This method will return: <br>https://mock-domain.com/api/news</p><pre>public getProductListByCountryAndPostalCodeEndpoint(<br>  countryCode: string, <br>  postalCode: string<br>): string {<br>  return this.createUrlWithQueryParameters(<br>    &#39;productlist&#39;, <br>    (qs: QueryStringParameters) =&gt; {<br>      qs.push(&#39;countryCode&#39;, countryCode);<br>      qs.push(&#39;postalCode&#39;, postalCode);<br>    }<br>  );<br>}</pre><p>This method will return:<br>https://domain.com/api/productlist?countrycode=en&amp;postalcode=12345</p><pre>public getDataByIdAndCodeEndpoint(<br>  id: string,<br>  code: number<br>): string {<br>  return this.createUrlWithPathVariables(&#39;data&#39;, [id, code]);<br>}</pre><p>This method will return:<br>https://domain.com/api/data/12/67</p><p>Now, let’s go to a component and use them all together.</p><pre>constructor(<br>  // Application Services<br>  private apiHttpService: ApiHttpService,<br>  private apiEndpointsService: ApiEndpointsService<br>) {</pre><pre>ngOnInit() {<br>  this.apiHttpService<br>      .get(this.apiEndpointsService.getNewsEndpoint())<br>      .subscribe(() =&gt; {<br>        console.log(&#39;News loaded&#39;))<br>      });<br>}</pre><p>All of the above are required for a large-scale application, but even for a small one, they’re useful.</p><h3>Resources</h3><p>The code for this piece can be found on GitHub <a href="https://github.com/georgeroubie/Angular-API-calls-the-right-way">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=264198bf2c64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/angular-api-calls-the-right-way-264198bf2c64">Make API Calls the Right Way in Angular</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular — CSS Variables Utility]]></title>
            <link>https://george-roubie.medium.com/angular-css-variables-utility-1a828c0d2aba?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a828c0d2aba</guid>
            <category><![CDATA[css-variables]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[scss]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Wed, 23 Oct 2019 21:07:33 GMT</pubDate>
            <atom:updated>2019-10-24T07:13:33.312Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular — CSS Variables Utility</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvN2Kw223G5zPiDpJ5HMsg.png" /></figure><p>In every Front-End project instead of CSS I use SCSS (CSS with super powers), because the features of SCSS are many and helpful in large scale applications.</p><p>One of my favorites feature is the SCSS variables, that helps you with the pattern DRY (don’t repeat yourself). But the disadvantage is that these variables are not accesible from the JavaScript.</p><p>This problem can be solved with the CSS Variables, also known as CSS Custom Properties.</p><p><em>CSS Variables are entities defined by CSS authors that contain specific values to be reused throughout a document.</em></p><p>I created an Angular Utility (Service) that gets and sets the value of a CSS Variable.</p><pre><a href="http://twitter.com/Injectable"><strong>@Injectable</strong></a><strong>()</strong><br>export class <strong>CssVariablesUtility</strong> {<br>  public <strong>getValue</strong>(<strong>propertyName</strong>: string): string | null {<br>    try {<br>      const root: HTMLElement = document.documentElement;<br>      const value: string =                        <br>            getComputedStyle(root).getPropertyValue(propertyName);<br>      return value ? value.trim() : null;<br>    } catch(ex) { return null; }<br>  }</pre><pre>  public <strong>setValue</strong>(<strong>propertyName</strong>: string, <strong>newValue</strong>: string): void {<br>    try {<br>      const root: HTMLElement = document.documentElement;<br>      root.style.setProperty(propertyName, newValue);<br>    } catch (ex) { }<br>  }<br>}</pre><p>You can download the above code from <a href="https://github.com/georgeroubie/Angular-CssVariablesUtility">here</a>.</p><p><em>REAL LIFE PROBLEM</em></p><p>Let’s say that you have a top menu in an application, that has a height of 50 pixels. And you want to create a DOM element with JavaScript and the height of this element must be the viewport minus the top menu height.</p><p>You can set the height of the element to this: <strong>calc(100vh — 50px)</strong> . But if the top menu is changed you must also change the height of the JavaScript element and I am pretty sure that you will forget it.</p><p>Let’s use CSS Variables and the CSSVariablesUtility to solve this.</p><p>In the CSS we will add this:</p><pre>/* Variables */<br><strong>:root</strong> { <br>  <strong>--topmenu-height</strong>: 50px;<br>}</pre><pre>/* Menu */<br>.top-menu {<br>  height: <strong>var(--topmenu-height)</strong>;<br>}</pre><p>And in the JavaScript we will add this:</p><pre>constructor(<br>  private cssVariablesUtility: CssVariablesUtility<br>}</pre><pre>ngAfterViewInit() {<br>  const topMenuHeight: number = <strong>this.cssVariablesUtility<br>                                    .getValue(&#39;--topmenu-height&#39;)</strong>;<br>  el.style.height = <strong>`calc(100vh - ${topMenuHeight})`</strong>;<br>}</pre><p>Now the height of the element is based on the CSS!!!</p><p><em>If you </em><strong><em>enjoyed</em></strong><em> this, </em><strong><em>please Clap</em></strong><em> it up and </em><strong><em>give a star</em></strong><em> to the </em><a href="https://github.com/georgeroubie/Angular-CssVariablesUtility"><strong><em>repository</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a828c0d2aba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extend Ionic 1 Grid with SCSS]]></title>
            <link>https://george-roubie.medium.com/extend-ionic-1-grid-with-scss-e9ecf40f8e8?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9ecf40f8e8</guid>
            <category><![CDATA[scss]]></category>
            <category><![CDATA[ionic]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Tue, 22 Oct 2019 19:02:37 GMT</pubDate>
            <atom:updated>2019-10-22T19:02:37.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*wTmAbomiXAWQvPrTekPglA.png" /></figure><p><strong>Ionic 1</strong> is an open source <strong>mobile app development framework</strong>, licensed under MIT, for developing native and progressive web apps with ease. It is actually a great way to bridge the gap between AngularJS web apps and hybrid mobile apps!</p><p>Ionic’s grid system is different than most, because of its use of the CSS Flexible Box Layout Module standard. The advantage is that the devices that Ionic supports, all support flexbox. There’s no restriction to a 12 column grid, or having to explicitly state how large each column should be.</p><p>Explicit Column Percentage Classnames:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*3nLQfO5hVovwRB6d01gNrA.png" /></figure><p>But you cannot have one column to be 30% and the other 70% in a row. You have to use the above percentages.</p><p>If you use Ionic with the <strong>SCSS</strong> version (CSS with superpowers) you can extend the above classes with this code:</p><pre>// Extend ionic sass grid<br>@for $i from 1 through 100 {<br>    .col-#{$i} {<br>        @include flex(0, 0, percentage($i)/100);<br>        max-width: percentage($i)/100;<br>    }<br>}</pre><p>But you may need to extend the column offset too, with the following code:</p><pre>// Extend ionic sass grid offset<br>@for $i from 1 through 100 {<br>    .col-offset-#{$i} {<br>        margin-left: percentage($i)/100;<br>    }<br>}</pre><p>You may download the above code from <a href="https://gist.github.com/georgeroubie/9301e864c178f6dac51720374db0bc40"><strong>here</strong></a>.</p><p><em>Originally published at </em><a href="http://blog.sieben.gr/blog/extend-ionic-grid-with-sass"><em>blog.sieben.gr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9ecf40f8e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five reasons why I love Orchard CMS]]></title>
            <link>https://george-roubie.medium.com/five-reasons-why-i-love-orchard-cms-2c25dcc0413b?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c25dcc0413b</guid>
            <category><![CDATA[cms]]></category>
            <category><![CDATA[orchard]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 19:38:34 GMT</pubDate>
            <atom:updated>2021-10-18T14:11:47.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*bAkY3UITdLjQHyV6VkTLeQ.png" /></figure><p>There are many Content Management Systems (CMS) available nowadays and as Front-End developer, I’ve tested a bunch of them. Τhe first version I used was Orchard 1.7. Since then, I’m implementing many web applications, with the latest version of Orchard (1.10.3). Orchard is a free, open source, community-focused Content Management System built on the ASP.NET MVC platform.</p><p>When setting up a new website, there are a lot of factors to consider, like your design and domain name, but the most important of all is choosing the right platform. This is crucial and not a decision to be taken lightly.</p><p><strong>There are three</strong> <strong>ways</strong> <strong>you can use Orchard CMS</strong>:</p><ul><li>If you are a <strong>Module Developer,</strong> you can download the entire solution from the <a href="https://github.com/OrchardCMS/Orchard">GitHub</a>.</li><li>If you are a <strong>Theme Developer,</strong> you can download the Orchard CMS Web Version from the <a href="https://www.microsoft.com/web/gallery/orchardcms.aspx">Microsoft Web Application Gallery</a>. The easiest way to do this is with the Microsoft WebMatrix. The installation is fast and you do not even need SQL Server because Orchard CMS can run with SQL Server Compact.</li><li>If you are a <strong>User, </strong>who wants to use only the Themes and Modules that community has created, you can sign up and create any number of Orchard sites you want in <a href="https://dotnest.com/">DOTNEST</a>. DOTNEST is the Orchard content management framework as software as a service.</li></ul><h3>My Favorite Features</h3><h3>1. Shape Tracing and Placement.info</h3><p>Content customization is a piece of cake with the combination of Shape Tracing and Placement.info. Shape Tracing is a module, that lets you see and generate from a user interface, all the shapes of a content. A content consists of parts and fields. These parts and fields are views files (Razor), called “Shapes”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*RmUNESuILGgHxQDC.png" /></figure><p>With the Shape Tracing, you can see the Model and the Placement of the selected Content.</p><p>The Placement.info is an XML file that can:</p><ul><li>Change the order of a shape</li><li>Change the zone of a shape</li><li>Remove a shape</li><li>Change the shape name</li></ul><p><strong>Example:</strong></p><pre>&lt;Match ContentType=&quot;Page&quot;&gt;<br>    &lt;Match DisplayType=&quot;Detail&quot;&gt;<br>        &lt;Place Parts_Title=&quot;Header:1;Wrapper=Page_Title&quot; /&gt;<br>        &lt;Match Path=&quot;/&quot;&gt;<br>            &lt;Place Parts_Title=&quot;Header:1;Wrapper=Page_Title_Home&quot; /&gt;<br>        &lt;/Match&gt;<br>        &lt;Place Parts_Tags_ShowTags=&quot;Header:2&quot; /&gt;<br>        &lt;Place Parts_Localization_ContentTranslations=&quot;Content:1&quot; /&gt;<br>        &lt;Place Parts_Layout=&quot;Content:2&quot;/&gt;<br>        &lt;Place Parts_Common_Metadata=&quot;Footer:1&quot; /&gt;<br>    &lt;/Match&gt;<br>&lt;/Match&gt;</pre><h3>2. Dynamic Forms</h3><p>You can create any number of forms in your website with ‘drag and drop’ functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/0*xR_tEZF05pjp2h84.png" /></figure><p>Every form has editable features:</p><ul><li>Client Validation for better UX</li><li>Store the submitted form into the database</li><li>HTML encode submitted values to prevent code injection</li><li>Notification message that users see after the form has been submitted</li><li>Redirect URL after the form has been submitted</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*Eescby4un0H8s3EY.png" /></figure><h3>3. Blogs</h3><p>Orchard’s Blog module is really great and easy to use. You can create as many blogs as you want. Some of the features are the following:</p><ul><li>Categorize your blog posts with Tags</li><li>Recent blog posts widget</li><li>Publish later a blog post</li><li>User roles for Editor and Authors</li><li>Blog Post Comments</li><li>Blog RSS Feed</li><li>Tag RSS Feed</li></ul><h3>4. Dashboards</h3><p>With the new Dashboards module, you can customize the Dashboard page explicitly for your client. For example, you can create a form that your client will use for contacting the customer support. Or, you can add a video tutorial for the CMS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/0*3ZJyrKOoNE13tNRy.png" /></figure><h3>5. Audit Trail</h3><p>With the Audit Trail module, you can see the progress of a Content. You may restore your content to a previous version and if you delete it, you can restore it. Finally, audit trail provides support for role related events and user related events.</p><p>For those features and other more functionalities, I will definitely suggest Orchard CMS for your next Website.</p><p><em>Originally published at </em><a href="http://blog.sieben.gr/blog/five-reasons-why-i-love-orchard-cms"><em>blog.sieben.gr</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c25dcc0413b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orchard CMS — Hide Elements from Layout Part]]></title>
            <link>https://george-roubie.medium.com/orchard-cms-hide-elements-from-layout-part-77d50726db92?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/77d50726db92</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[cms]]></category>
            <category><![CDATA[orchard]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 19:15:14 GMT</pubDate>
            <atom:updated>2019-10-21T19:15:14.373Z</atom:updated>
            <content:encoded><![CDATA[<h3>Orchard CMS — Hide Elements from Layout Part</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*g9L_MDq6fhQqHJG1Xqa1gQ.jpeg" /></figure><p>Layout Part in Orchard CMS is a very powerful tool, but it is complicated for the end user (content editor), as you can see in this picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*thgDZO51KTGdm8JF.PNG" /></figure><p>Also the Dashboard sometimes can be complicated for a non-developer user. In almost every Orchard CMS Website, I use in <strong>TheAdmin</strong> Theme a <strong>noadmin.css</strong> file. This file is called only when the user in not the Admin and hides things from the end user.</p><p>Add the<strong> noadmin.css</strong> file in the Styles folder in the TheAdmin Theme. Add these line of code in the TheAdmin Theme in the Layout.cshtml file to call the noadmin.css file:</p><pre>if(!AuthorizedFor(Orchard.Security.StandardPermissions.SiteOwner)) {<br>    Style.Include(&quot;noadmin.css&quot;).AtHead();<br>}</pre><p>The easiest to understand elements for a Content Editor, and absolutely necessary are:</p><ul><li>Grid</li><li>Row (1 col, 2 col, 3 col, 4 col, 6 col, 12 col)</li><li>HTML</li><li>Image</li></ul><p>Your Layout Part will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/0*mK5IMzDlby9hINbm.PNG" /></figure><p>Feel free to edit the noadmin.css for any change you want to do to the Dashboard.</p><p>You can download the above files from my <a href="https://github.com/georgeroubie/Hide-Elements-from-Layout-Part-Orchard-CMS"><strong>GitHub</strong></a>.</p><p><em>Originally published at </em><a href="https://orchardtricks.dotnest.com/blog/hide-elements-from-layout-part-orchard-cms"><em>https://orchardtricks.dotnest.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77d50726db92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orchard CMS — Content Carousel]]></title>
            <link>https://george-roubie.medium.com/orchard-cms-content-carousel-8dc33390cac7?source=rss-b611ee7ec76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dc33390cac7</guid>
            <category><![CDATA[cms]]></category>
            <category><![CDATA[carousel]]></category>
            <category><![CDATA[bootstrap-3]]></category>
            <category><![CDATA[orchard]]></category>
            <dc:creator><![CDATA[George Roubie]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 19:01:30 GMT</pubDate>
            <atom:updated>2019-10-21T19:01:30.402Z</atom:updated>
            <content:encoded><![CDATA[<h3>Orchard CMS — Content Carousel</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*EXpf2xVv1ET8A7_NSdMpBw.png" /></figure><p>Every website needs a Carousel (Image Slider) and this is a content that I use almost in every Orchard CMS Project.</p><p><strong>Installation</strong>:</p><ul><li>Enable <strong>Import Export</strong> Module</li><li>Enable <strong>Razor Templates</strong> Module</li><li>Import <a href="https://github.com/georgeroubie/content-carousel-orchard-cms"><strong>Carousel.xml</strong></a></li></ul><p>This is a Bootstrap Carousel, so you must have Bootstrap installed to your Orchard Site. Bootstrap 3 is already installed in <a href="https://github.com/georgeroubie/bootstrap-3-orchard-cms-theme">this</a> head start Orchard CMS theme.</p><p>One the other hand if you do not want Bootstrap Carousel to your site, you can use the carousel you prefer. The only thing you have to do is to change the template <strong>Content_Detail__Carousel</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5RRIgklfczHf-FaH.png" /></figure><p><strong>How to use it</strong>:</p><p>In your Layout Part, will appear in the Content Items Section, a <strong>Carousel</strong> item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*TnBph2KuYM0l-JDf.png" /></figure><p>You can drag it wherever you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/0*Z8kMQRuprxYh3lH1.png" /></figure><ul><li><strong>Title</strong>: The title of the carousel content</li><li><strong>CSS classes</strong>: You can add Custom css classes for the carousel content</li><li><strong>Carousel Image</strong>: You can add as many images you want. You can edit an Image and you can add a Caption.</li><li><strong>Time in seconds</strong>: The amount of time in seconds to delay between automatically cycling an image.</li></ul><p>Click <strong>Save</strong> and you are ready.</p><p><em>Originally published at </em><a href="https://orchardtricks.dotnest.com/blog/content-carousel-orchard-cms"><em>https://orchardtricks.dotnest.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dc33390cac7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>