singleton design pattern example in javascript

const Singleton = (function () {
    let instance;
 
    function createInstance() {
        const object = new Object("I am the instance");
        return object;
    }
 
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

const object1 = singleton.getInstance();
const object2 = singleton.getInstance();

console.log(object1 === object2); //true

Execute async functions in Series


const asyncTask = function(i) {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(`Completing ${i}`), 100*i)
  });
}

const promises = [
  asyncTask(3),
  asyncTask(1),
  asyncTask(7),
  asyncTask(2),
  asyncTask(5),
];

asyncSeriesExecuter = async (promises)=> {
 
  for(let i=0; i<promises.length; i++) {
     await promises[i].then((data)=>{
       console.log(data)
     })
  }
 

 
}

asyncSeriesExecuter(promises);

How to find max and min value in array

let intArray = [600,6,500,1];
let min=0;
let max=0;
intArray.forEach((data)=>{
 
  if(data > max) {
    max=data;
    min=data;
  }else if(data < min) {
    min = data
  }
 
})

console.log(min);
console.log(max);

How to get the value of state after using setState in React

this.setState({ name: "Hello Chris1993!" }, () => {
  console.log(this.state.name); // output: Hello Chris1993!
});


For Functional Component Use useEffect.

useEffect(() => {
  console.log(state) // do something after state has updated 
}, [state]) 

Get difference between 2 dates in JavaScript

const date1 = new Date('10/15/2020');
const date2 = new Date('12/1/2020');

const diffTime = Math.abs(date2 - date1); // time in milliseconds
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); // convert time to days

Note: Difference in date always return in milliseconds.

How to remember

- 1000 Milliseconds to 1 Sec
- 60 Sec 1 Minute
- 60 Min 1Hr
- 24 Hr to 1 Day

React : Use Single Handler to update all input textbox


    const handleUpdateInput = (e) => {
        let key = e.target.name;
        setEmpData({
            ...empData,
            [key]:e.target.value
        })

    }

7 - ES6 Features

- let & const 
- Arrow Functions
- Template literals
- Default Parameter value 
- Spread and rest 
- destructuring  
   const { name } = person;
- object literals 
    let person = { name } // key and value is same 

What is useCallback and Why it's required.


The useCallback hook is used where we have to check the reference equality (i.e functions, callback functions)

where we have normal props check we can user React.Memo ( remember React.Memo is nothing to do with useMemo hook )

useCallback is mainly used when we pass function as callback function in react components


Before Using Callback


const incrementSalary = () => {
   setSalary(salary + 1000 )
}


After Using callback funcation

const incrementSalary = useCallback(() => {
   setSalary(salary + 1000 )
}, [age])

Pure Memoization in JavaScript | Closures Example

function square(num) {
  return num * num;
}

function memoizedSquare() {
  let cache = {}
  return function optimizedSquare(num) {
    //console.log(JSON.stringify(cache));
    if(num in cache) {
      console.log('returning from cache);
      return cache[num];
    }else {
      console.log('computing square');
      const result = square(num);
      cache[num] = result;
      return result;
    }
  }
}

const memoSquare = memoizedSquare();
console.log(memoSquare(10));
console.log(memoSquare(20));
console.log(memoSquare(30));
console.log(memoSquare(30));

What is Closures is javascript

Closures 

Function along with its lexical scope bundled together forms a closure. it's called Closures.

How to cancel/abort ajax request in axios

useEffect(() => {    const ourRequest = Axios.CancelToken.source() // <-- 1st step      const fetchPost = async () => {      try {        const response = await Axios.get(`endpointURL`, {          cancelToken: ourRequest.token, // <-- 2nd step        })        console.log(response.data)        setPost(response.data)        setIsLoading(false)      } catch (err) {        console.log('There was a problem or request was cancelled.')      }    }    fetchPost()      return () => {      ourRequest.cancel() // <-- 3rd step    }  }, [])

Add preact in nextjs


  webpack: (config, { isServer }) => {
   // config.plugins.push(new webpack.EnvironmentPlugin(myEnv));

    if (!isServer) {
      Object.assign(config.resolve.alias, {
        react: 'preact/compat',
        'react-dom/test-utils': 'preact/test-utils',
        'react-dom': 'preact/compat',
      });
    }


    return config;
  }