Skip to Content

memoize()

Store data in a temporary cache so that “expensive” functions do not need to be executed more than once.

JavaScript April 4, 2021

Usage

JavaScript
nebula.memoize(action, handle, value)

Parameters

action
(Required) (String) Whether to "get" or "set" the cache for the desired handle
Default: None

handle
(Required) (String) The name of the cache to use
Default: None

value
(Optional) (Mixed) The value to associate with the handle
Default: None

Parameter Notes

Note the value is only required when using the “set” action.

Handles can be human-readable strings and are not case-sensitive.

Request or provide clarification »

Examples

Use it to call an expensive function

JavaScript
let example = nebula.memoize('get', 'my first memoize');
if ( !example ){
    example = nebula.memoize('set', 'my first memoize', expensiveFunctionHere()); //memoize returns the value so it can be used inline like this
}

console.log('Result:', example); //Use the result of the expensive function now

Use it inside of an expensive function

JavaScript
function expensiveFunctionHere(){
    let example = nebula.memoize('get', 'my expensive function');
    if ( !example ){
        let example = 42; //Do the expensive functionality now        
        nebula.memoize('set', 'my expensive function', example);
    }
    
    return example;
}

Additional Notes

The Nebula memoize function is treated similarly to the WordPress Transient API.

Source File

Located in /assets/js/modules/utilities.js on line 427.

No Hooks

This function does not have any filters or actions available. Request one?
JavaScript
nebula.memoize = function(action, handle = '', value = false){
    nebula.memoizeCache = nebula.memoizeCache || {};

    if ( action.toLowerCase() === 'set' ){
        nebula.memoizeCache[handle] = value;
        return value; //Returning the set value allows for memoize to be set inline with the calculated value if desired
    }

    if ( action.toLowerCase() === 'get' ){
        if ( handle in nebula.memoizeCache ){
            return nebula.memoizeCache[handle];
        }
    }

    return false;
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.memoize = function(action, handle, value){
    //Write your own code here, leave it blank, or return false.
}