Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

caching in javascript

// to create a cache, you can use an IIFE to return a function with access to a local variable:
const functionWithCache = (function() {
	const cache = {};
	return function(num) {
		// example: returns whether an input number is even or not
		return num % 2 === 0;
	};
})();

// you can use this to memoize functions:
const memoizedFunction1 = (function() {
	const cache = {};
	return function(num) {
		if (num in cache) {
			return cache[num];
		}
		// example: returns whether an input number is even or not
		return cache[num] = num % 2 === 0;
	};
})();

// for more complex parameters:
const memoizedFunction2 = (function() {
	const cache = {};
	return function() {
		const cacheQuery = Array.from(arguments).map((arg) => JSON.stringify(arg)).join(",");
		if (cacheQuery in cache) {
			return cache[cacheQuery];
		}
		// function body
		return cache[cacheQuery] = result;
	};
})();

// with that we can create a function to convert other functions into memoized functions:
function memoize(func) {
	const cache = {};
	return function() {
		const args = Array.from(arguments);
		const cacheQuery = args.map((arg) => JSON.stringify(arg)).join(",");
		if (cacheQuery in cache) {
			return cache[cacheQuery];
		}
		return cache[cacheQuery] = func(...args);
	};
}
Comment

What is caching on js?

Caching is a common technique for making your applications faster. It lets you avoid slow operations by reusing previous results. In this article, Ayo Isaiah walks us through the different options for caching in NodeJS applications
Comment

PREVIOUS NEXT
Code Example
Javascript :: react onchange url 
Javascript :: react new project 
Javascript :: chrome.browseraction.getbadgetext 
Javascript :: npm modal 
Javascript :: puppeteer set up code 
Javascript :: Warning: Internal React error: Expected static flag was missing. Please notify the React team. 
Javascript :: ubuntu apps to install 
Javascript :: jq storage object on refresh 
Javascript :: How to add click event to table row js 
Javascript :: filter buttons react 
Javascript :: ajax add custom header 
Javascript :: js export options 
Javascript :: json concat 
Javascript :: greater than or equal to javascript 
Javascript :: set a variable in express.js 
Javascript :: upload bloob javascript 
Javascript :: react double render 
Javascript :: upload photos cypress 
Javascript :: angularjs ng-options name value 
Javascript :: jquery dom traversal parent 
Javascript :: decode jwt tokens 
Javascript :: date match mongodb 
Javascript :: exclude vales from array in js 
Javascript :: node js 
Javascript :: javascript eventlistener 
Javascript :: javascript get response payload 
Javascript :: words counter in javascript 
Javascript :: label tag alternative in react native 
Javascript :: jquery get return jquery object 
Javascript :: javascript addeventlistener pass parameters 
ADD CONTENT
Topic
Content
Source link
Name
5+4 =