8/17/19

Deboundce In The Javascript

Intro

I decided to wrote here all the things i know about the "debounce" termin
So: by saying "debounce" people mean - some functionality that blocks multiple event handlers from trigger until some specified time interval (like one second) passed.

Example: scroller, that fires lots of "scroll" events when user scrolling down, should respond only to last scroll event within second (specified time interval) and ignore all the rest of events within that second.

Implementation

The key thing for implementing debounce - is to know about "clearTimeout" method, which cancels the previously scheduled actions:


let timer = null;
const debounce = (fn, delay) => {
  // clean previously scheduled actions
  clearTimeout(timer);
  // scheduled  the last action
  timer = setTimeout(fn, delay);
};

document
  .querySelector("#myInput")
  .addEventListener("input", e =>
    debounce(_ => console.log(e.target.value), 1000)
  );
// you will see only last event appears after the delay

Or, if you want to store "timer" inside the function without polutting global scope:


var debounce = (fn, time, immediate) => {
  let timeout;
  return (...rest) => {
    const [args] = rest;

    const later = () => {
      if (!immediate) {
        timeout = null;
        fn(args);
      }
    };

    const callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, time);

    if (callNow) {
      fn(args);
    }
  };
};
…

document
  .getElementById("app")
  .addEventListener("input", debounce(handle, 1000));

function handle(e) {
  console.log(e.target.value);
}


8/6/19

Why Do You Need "Set" In Javascript

Lets start with explain what is set.
In the old times the only way to store some data list was by using array:

const users = ['Moshe','Vasia'];


These days some new players entering the scene:
The Set
It has "add", "delete", "clear" (for remove all the entries) methods

const users = new Set(['Moshe', 'Vasia']);
users.add('Ivan'); // will add one more entry

It also has "has" method for checking if item exists in Set:

console.log(users.has('Ivan')); // will print true

As far as I can see - the most cool feature (and may be a purpose of Set`s creation) - is uniqness: Set will not allow duplicates:

console.log(new Set([1,2,4,3,1])); // will 1,2,4,3

BUT (there must be always a "but")
all those cool features will not help you with following structure: (if the array consist of objects)

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

You will not be able to check if somebody with id '123' exist in Set using "has" method:

console.log(users.has('123')); // will be false

Also: it appears that Set not has a support for accessing entries by index And if you want to access first entry you will need to use something like this:

const user = users.values().next().value;
console.log(user); // will print "{id:123, name: 'Moshe'}"

Disappointing!
So, when this "Set" might be needed? you may ask...
The answer I found so far - is following scenario:
Remove duplicates:

const users = [
   {id:123, name: 'Moshe'},
   {id:124, name:'Vasia'},
   {id:125, name:'Ivan'},
   {id:123, name: 'Moshe'}// same Moshe one more time
];
const dedupedIds = Array.from(new Set(users.map(({id}) => id)))
console.log(dedupedIds); // will print 123,124,125

Conclusion

Although Set looks cool and promising - it seems there is not a much cases to use it (As far as I can see now)

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

Deboundce In The Javascript

Intro I decided to wrote here all the things i know about the "debounce" termin So: by saying "debounce" people mean -...