简体   繁体   中英

JavaScript cache return value of a function with more than one parameter

I'm going through John Resig's snippets on advanced JavaScript . On #19 he mentions a method to cache the return value of a function. What's the best way to cache the return value of a function that has more than one parameter?

There has to be a much better way than stringify-ing the recieved arguments and using that as the key for the cache object:

function $$(selector, el) {
    var cacheKey = JSON.stringify(arguments);
    if ($$.cache[cacheKey]) return $$.cache[cacheKey];

    return ($$.cache[cacheKey] = NodeListToArray( (el || document).querySelectorAll(s) ));
}
$$.cache = {};

You could use a custom hash function that can operate on objects. But hash functions cause collisions and would require significantly more code than your simple example.

Or you could make the cache n-dimensional, where n is the number of arguments. So essentially this:

function $$(selector, el) {
    if ($$.cache[selector] && $$.cache[selector][el])
        return $$.cache[cacheKey][el];
    // etc.

That assumes that both selector and el are able to be used as object keys. You may need to stringify them in another manner.

Just consider an array element,

JSON (JavaScript Object Notation) works with generic platform, so for easy use you must create a function for your use,

Here, $$.cache[0] is your easy way after reading the cachekey ,

If we make thing more easy, we might have security problem later.

I hope this will satisfy your requirement :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM