Skip to content

Instantly share code, notes, and snippets.

import { useState, useEfftect, useRef } from "react";
const useStateWithcallback = (initialState) => {
const [state, setState] = useState(initialState);
const callbackRef = useRef(null);
const setStateWithCallback = (newState, callback) => {
callbackRef.current = callback;
setState(newState);
};
@satyam4p
satyam4p / cachedApiCAll.js
Last active July 20, 2024 15:54
Implement a function that caches the API response for given expiry time if new call is made between the expiry time then return cached result else make new call
//Problem Statement
//Implement a function in JavaScript that caches the API response for the given amount of time.
//If a new call is made between that time, the response from the cache will be returned,
//else a fresh API call will be made.
/**
*
* @param {*} expiryTime in ms
*/
function cachedApi(expiryTime) {
//Problem Statement
//Implement a function in JavaScript that caches the API response for the given amount of time.
//If a new call is made between that time, the response from the cache will be returned,
//else a fresh API call will be made.
/**
*
* @param {*} expiryTime in ms
*/
function cachedApi(expiryTime) {
@satyam4p
satyam4p / polyfills.js
Created July 19, 2024 16:41
javascript polyfills
/**
* Array map polyfill
* @param {*} callback
* @returns
*/
function myMap(callback) {
let newArr = [];
for (let i = 0; i < this.length; i++) {
newArr.push(callback(this[i]));
@satyam4p
satyam4p / memoizedFibonacci.js
Created March 2, 2024 06:26
Return sum of even numbers in fibonacci series which are even.
let cache = [];
function fib(num) {
if (cache[num] == undefined) {
if (num == 0) {
cache[0] = 0;
} else if (num == 1) {
cache[1] = 1;
} else {
cache[num] = fib(num - 1) + fib(num - 2);
}
@satyam4p
satyam4p / AsyncTasksParallelExecution.js
Created March 2, 2024 06:08
Snippet for Running async tasks in parallel
/**generates async tasks */
function asyncTask() {
return new Promise((resolve, reject) => {
let val = Math.floor(Math.random() * 10);
if (val > 5) {
resolve(val);
} else {
reject(val);
}
});
@satyam4p
satyam4p / revealingEventEmitter.js
Created January 14, 2024 05:48
Revealing constructor pattern example through event emitter
const EEStoEventMaps = new WeakMap();
export default class EventEmitter{
constructor(publisher){
const eventMap = Object.create(null);