hooks_use-cache.js

import { React } from '@gravityforms/libraries';

const { useState } = React;

/**
 * @function buildCacheKey
 * @description Build a cache key.
 *
 * @since 4.0.2
 *
 * @param {string} prefix    The prefix for the cache key.
 * @param {Array}  paramKeys The keys of the parameters to build the cache key.
 * @param {object} params    The parameters to build the cache key.
 *
 * @return {string} The cache key.
 */
export const buildCacheKey = ( prefix = '', paramKeys = [], params = {} ) => {
	return paramKeys.reduce( ( carry, paramKey ) => {
		if ( ! params[ paramKey ] ) {
			return carry;
		}
		return `${ carry }-${ params[ paramKey ] }`;
	}, prefix );
};

/**
 * @function useCache
 * @description A hook to manage a cache.
 *
 * @since 4.0.2
 *
 * @param {object} initialState The initial state of the cache.
 *
 * @return {object} The cache state and actions.
 */
export const useCache = ( initialState = {} ) => {
	const [ cache, setCache ] = useState( () => initialState );

	const addCache = ( key, value ) => {
		setCache( ( prevCache ) => ( {
			...prevCache,
			[ key ]: value,
		} ) );
	};

	return {
		cache,
		addCache,
	};
};