Skip to Content
Menu

memoize()

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

JavaScript October 3, 2024

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;
}

🚫 Example of unintentional DOM thrashing (Bad!)

JavaScript
jQuery.each(bigObject, function(index, data){
    if ( jQuery('body.container-prepared').length ){ //This checks the DOM for every item in the loop– this is not performant!!
        //Do something with the datapoints within the big object
    }
});

✅ Prevent unintentional DOM thrashing (Good!)

JavaScript
//Remember: you can memoize "states" too!
jQuery.each(bigObject, function(index, data){
    if ( nebula.memoize('get', 'container prepared') || jQuery('body.container-prepared').length ){ //This will only parse the DOM once (the first time it checks)        
        nebula.memoize('set', 'container prepared', true); //Now future checks will not need to touch the DOM at all
        
        //Do something with the datapoints within the big object
    }
});

Additional Notes

Remember that even the functionality that memoize is caching does not have to be that “expensive” to see benefits from it. If you are using a lot of jQuery selectors or frequently reading/checking the DOM you may be “DOM Thrashing” and not realizing it. Memoization can dramatically help this by storing the state of the DOM in an object instead of needing to constantly check the “length” of an element (even a body class).

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

Was this page helpful? Yes No


    A feedback message is required to submit this form.


    Please check that you have entered a valid email address.

    Enter your email address if you would like a response.

    Thank you for your feedback!

    Source File

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

    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. Remember: Some functionality is conditionally loaded via dynamic imports, so if your function is not overriding properly, try listening for a DOM event (described below).

    JavaScript

    For non-module import functions:

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


    For dynamically imported module function overrides:

    jQuery(window).on('load', function(){
        nebula.memoize = function(action, handle, value){
            //Write your own code here, leave it blank, or return false.
        }
    });


    Custom Nebula DOM events do also exist, so you could also try the following if the Window Load listener does not work:

    jQuery(document).on('nebula_module_loaded', function(module){
        //Note that the module variable is also available to know which module specifically was imported
        if ( typeof nebula.memoize === 'function' ){
            nebula.memoize = function(action, handle, value){
                //Write your own code here, leave it blank, or return false.
            }
    	}
    });