Saturday, January 26, 2019

CSS Heart beating

We can make a heart with just css even having the only div.
  
<div id="heart"></div>

The most tricky part is to draw a heart. Luckily, it is pretty simple - it can be composed of 3 shapes - square and 2 circles. Square will be described with main css class, and 2 circles with ::before and ::after pseudo classes

And beating will be implemented with css @keyframe animation



Now let's have a look at the whole css.

Wednesday, January 23, 2019

JavaScript private fields

There is no private keyword in ES5 and ES6, so to create a private field we need to make up a workaround
  
function MyObj(val){
   let _val = val;
  
   return{
      getVal: function() { return _val; },
      setVal: function(newVal) { _val = newVal; }
  };
}

The MyObj(..) function is a factory that returns a new object every time we call it, so no necessary to use a new keyword. The object has 2 methods - getter and setter so that we can manipulate with the _val value
  
var o = MyObj(5);
console.log(o.getVal()); //5
o.setVal(8);
console.log(o.getVal()); //8

As long as _val is declared with the let keyword, it's impossible to access it directly from a different context
  
o._val = 10;
console.log(o.getVal()); //_val is still 8

o._val = 10 creates a completely separate property _val inside the object o, you can update it independently from our private field.

If for some reason you cannot use ES6, there is another solution:

Tuesday, January 15, 2019

JavaScript Array groupBy method

Array.prototype doesn't have any grouping functionality, so let's add the groupBy() method. Let's say we have the following array example:
  
var movies = [
                 {  
                   "Title": "Inception",
                   "Year": "2010",
                   "Director": "Christopher Nolan"
                },
                {  
                   "Title": "Interstellar",
                   "Year": "2014",
                   "Director": "Christopher Nolan"
                },
                {
                   "Title": "Avatar",
                   "Year": "2009",
                   "Director": "James Cameron"
                },
                {
                   "Title": "The Dark Knight",
                   "Year": "2008",
                   "Director": "Christopher Nolan"
                },
                {  
                   "Title": "Batman Begins",
                   "Year": "2005",
                   "Director": "Christopher Nolan"
                }
];

console.table(movies.groupBy('Director'));
The groupBy('Director') method should return 2 groups - 1st "Christopher Nolan" group and 2nd "James Cameron" group. Every group should contain the list of associated movies.

Now let's have a look at the method implementation.