Last active
January 16, 2022 22:58
-
-
Save CodeZombie/ec0c5975ca43b8ffa6a33986a7edd1b0 to your computer and use it in GitHub Desktop.
Dart arbitrary caching middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var CacheDatabase = Map(); | |
//An arbitrary function which returns a String | |
String sexNumberAsString() { | |
return "69"; | |
} | |
//Another arbitrary function which takes in arguments and returns a different type. | |
int add(int a, int b) { | |
return a + b; | |
} | |
//The cache middleware function. | |
//Takes in a function and an optional list of parameters. | |
dynamic cache(Function f, [List? params]) { | |
//Generate a unique key based on the two inputs. | |
String key = f.toString() + (params ?? "").toString(); | |
//Search the cache database for the key, returning the value if found. | |
if(CacheDatabase.containsKey(key)){ | |
print("Cache hit!"); | |
return CacheDatabase[key]; | |
} | |
//If we didn't find the key, run the function f and store it in the db. | |
print("Cache miss"); | |
var result = Function.apply(f, params); | |
CacheDatabase[key] = result; | |
return result; | |
} | |
void main() { | |
print(cache(add, [0, 0])); //Miss | |
print(cache(add, [20, 50])); //Miss | |
print(cache(add, [0, 0])); //Hit | |
print(cache(add, [20, 50])); //Hit | |
print(cache(add, [1, 2])); //Miss | |
print(cache(add, [1, 3])); //Miss | |
print(cache(add, [0, 0])); //Hit | |
print(cache(sexNumberAsString)); //Miss | |
print(cache(sexNumberAsString)); ///Hit | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment