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])