7/20/19

Array and Object And When to Use Each Of Them

Where are lot of articles about this exact subject around the web, but, since I feel this doesn't clear anought for me - I feel like write a post about...

Object(Old good javascript object)

Pretty common scenario - when you have list of objects came from API:


const users = [
  {id:'123', name: 'Moshe'},
  {id:'124', name: 'Vasia'},
]

and you need to access one of the objects by its 'id' - you can do it by searching through the array, like this:

const currentUser = users.find(({id}) => id === '123');

But, of course, if you have array with lot of users - it will be much quicker to access some certain user by id - if "users" were stored inside Object with following structure:

const users = {
  '123': {id:'123', name: 'Moshe'},
  '124': {id:'124', name: 'Vasia'},
}
const currentUser = users['123'];

BTW, for optimize your performance you can restructure the users collection from array to object using following code:

let optimizedUsers = users.reduce((acc, user) => {
  return {
    ...acc,
    [user.id]: user  
  };
}, {});
const currenttUser = optimizedUsers['123'];
console.log(currenttUser.name); // will print "Moshe" 

You just saw the scenario with advantage of using Object upon Array

7/16/19

3 Design Patterns With Javascript By Example

Hi readers. I decided to list here some 3 design patterns i knew (Or so i think) implemented with Javascript:

1. Observer

Lets start with Observer pattern:
the special thing about this pattern is that:
it keep tracking changes on some object, and if changes occurred - it broadcasts the changes the to dependent objects.

Subject

To implement the pattern in javascript we need firstly create a "subject":

let Subject = function() {
  let observers = [];
  return {
    subscribe(ob) {
      observers.push(ob)
    }
    unsubscribe(ob) {
      observers.splice(observers.indexOf(ob), 1)
    },
    notify(ob) {
      if(observers.indexOf(ob)===-1) {return;}
      observers[observers.indexOf(ob)].notify()
    }
  }
}

As you can see, subject must contain "subscribe", "unsubscribe", and "notify" methods and store all the "observers" at some inner storage/variable

Observers

Next thing - lets create the Observer object/class - the only thing it must have - is a "notify" method (for being notified)

let Observer = function(num){
 return { notify: () => console.log(`num ${num} notified`)}
}

Thats it - from now we can create observers, subscribe and notify to observers that subscribed:

let s = new Subject();
let ob1 = new Observer(1)
s.subscribe(ob1);
s.notify(ob1);
s.unsubscribe(ob1);
s.notify(ob1); // will not print, because it unsubscribed

The example of this pattern usage, is "addEventListener" method where we can subscribe to some browser events (like click)

2. Factory

This pattern lets users to create objects ONLY by using "creator" (not directly by using "new" keyword)


let CarCreator = function(modl) {
  switch(modl) {
    case "zaporojets":
     return new Zaporojets(); // only creator can use "new"
     break;
    case "volga":
     return new Volga(); // only creator can use "new"   
     break;
  }
 

The idea here to simplify the objects instantiation for users - they only need to supply the type of car as a string:

 let my= CarCreator("volga");


3. Singelton

The idea of this pattern is NOT to let creation of more than one instance of some object:
Here is one of the ways i can think of - not to let users to use "new" keyword:


var Singelton = (function(){
  function someObj() {
    return {
      name:'vasia'
    }
  }
  // only here you can use the 'new'
  return new someObj();
  
}())
console.log(Singelton.name);// will print "vasia"
console.log(new Singelton);// will cause error

The example of this pattern usage, can be the great old JQuery library - that allows you only to use their "$" object without any "new"s prior to it...

7/11/19

Hooks in React

What is this new React feature everybody is talking about?
Well, it seems the main problem it tries to solve is - how to use state inside functional components.
Functional... what?
Ok, lets start from the beginning:
Usually to build the component with React you should use the following syntax:

class HelloMessage extends React.Component {
  render() {
    return (
      <div>;
        Hello {this.props.name}
      </div>
    );
  }
}

It also called the class syntax
The Interesting thing is - this is not the only way. There is another way to create react component, it called functional :

function Example(props) {
   return  ( 
      <div>;
        Hello {this.props.name}
      </div>
     );
}

This way is much more simpler and clear and testable, because - it is just javascript function!
BUT! (There is always but) - one of the limitations of functional components is - that here you cannot use the "state" feature of React.
State - it is inner data of the component which is not accessible from the parent

class UserForm extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      username:'',
      lastname: ''
    };
  }
  render() {
    return (
      <form>
        username: <input value={this.state.username}/>  <br/>
        lastname:  <input value={this.state.lastname}/>
      </form>
    );
  }
}

ReactDOM.render(
  <UserForm  />,
  document.getElementById('user-form')
);

So now (from React 16.8 and later) you can use state feature event inside functional components (Yes You Can!)- by using following syntax:

import React, { useState } from 'react';

export default function Example() {
    const [userModel, setUserModel] = useState({username:'ss', lastname:'dd'});

    return (
      <form>
        username: <input value={userModel.username}/>  <br/>
        lastname:  <input value={userModel.lastname}/>
      </form>
    );
  }

Note that "setUserModel" is for modify the state:

<button onClick={()=>setUserModel({username: 'shlomo', lastname: 'shlomovitz'})}/>click</button>

Pretty Cool, huh?

7/6/19

Tagged Template Literals

Ok, everybody heard about "backticks" ES6 feature...


 const hero = 'Splinter'
 console.log(`My name is ${hero}`); 
// will print "My name is Splinter"

But recently I stumble upon following code I could not understand:

import { css, cx } from 'emotion'

const color = 'white'

render(
  <div
    className={css`
      padding: 32px;
      background-color: hotpink;
      font-size: 24px;
      border-radius: 4px;
      &:hover {
        color: ${color};
      }
    `}
  >
    Hover to change color.
  </div>
)

What is this strange syntax?

Tagged Template Literals

Well it appears you can tag a template with function
Like this:

 const hero = 'Splinter';

 const printHero = html`My name is ${hero}`;
 // here is the function:
 function html(strings, ...values) {
   let str = '';
   strings.forEach((string, i) => {
       str += `${string} ${values[i] || ''}`;
   });
   return str;
 }

/*
printHero will print:
"My name is  <span class='hl'>Splinter</span> <span class='hl'></span>"
*/

Using tagged template gives you ability to control the way the template is parsed.

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...