This package can be used in this scenario
- You have a costly function: time consuming, heavy CPU or IO usage
- You need to perform that function frequently
- The result of your function can change over time
- You can tolerate some -configurable- inconsistency
- You want to optimize that process
It stores in memory the result of your function for immediate access, and clears that memory after a specified time. It returns a function that can be used instead your original one.
const hold = require('@wjsc/hold-on');
const myOptimizedFunction = hold(<Your Function>, <Time in miliseconds>);
myOptimizedFunction();
const hold = require('@wjsc/hold-on');
// Define your costly function: Let's supose it's so heavy!
const myFunction = () => new Date();
// Make a new version of your function with 500 ms cache
const myOptimizedFunction = hold(myFunction, 500);
// This code will execute new Date() only once
for(let i = 0; i<50; i++){
// And it prints always the same date
console.log(myOptimizedFunction());
}
const hold = require('@wjsc/hold-on');
// Any HTTP client
const fetch = require('node-fetch');
const myFunction = () => fetch('https://httpstat.us/200')
.then(res => res.text());
const myOptimizedFunction = hold(myFunction, 5000);
// This code will execute the HTTP GET only once
for(let i = 0; i<50; i++){
myOptimizedFunction()
.then(console.log);
}
// If you call the function after 5000 ms
// the request will be executed again
const hold = require('@wjsc/hold-on');
const fs = require('fs');
const myFunction = () => new Promise((resolve, reject) => {
fs.readFile('./my-file', 'utf8', (err, data) =>
err ? reject(err) : resolve(data)
)
})
const myOptimizedFunction = hold(myFunction, 5000);
myOptimizedFunction().then(console.log);
const hold = require('@wjsc/hold-on');
const aws = require('aws-sdk');
aws.config.update({
secretAccessKey: 'ABCDE',
accessKeyId: '12345'
})
const s3 = new aws.S3();
const myFunction = () => {
return new Promise((resolve, reject) => {
s3.getObject({
Bucket: 'my-bucket',
Key: 'my-file'
}, (err, data) => {
if ( err ) reject(err)
else resolve(data.Body.toString())
})
})
}
const myOptimizedFunction = hold(myFunction, 5000);
myOptimizedFunction().then(console.log);
Every line of code is tested https://github.com/wjsc/hold-on/blob/master/test/index.test.js
Less than 20 lines of code and no dependencies
This function uses setTimeout to clear the internal cache. In some cases, you may need to clear this timer. This can be usefull if you are running a script that doesn't end at desired time, or if you want to terminate a background timer.
const myFunction = () => {};
const myOptimizedFunction = hold(myFunction, 100000000);
clearInterval(myOptimizedFunction.interval);
Just use the original function, or create a new function version.
Package name reference: https://www.youtube.com/watch?v=WPnOEiehONQ