Time string conversion library
This library is used for converting time strings, e.g. 1 month
, to an integer value relative to another unit.
Example
const tsUnit = ; tsUnit; // 3600000tsUnit; // 3600000tsUnit; // 60000tsUnit; // 60000tsUnit; // 3660000
API
You can require the module in several ways:
Default
const tsUnit = ; tsUnit; // 3600000tsUnit; // 3600tsUnit; // 3660000
Prototype
Modifies the String
prototype. NOT RECOMMENDED
const tsUnit = ; '1 hour'; // 3600000'1 hour'; // 3600'1h 1min'; // 3660000
Tag
Using the custom interpolation feature of ES6:
const tsUnit = ; tsUnit `1 hour`; // 3600000tsUnit ` 1 hour`; // 3600tsUnit `1h 1min `; // 3660000
What for?
This library was created because I was sick of having a mix of millisecond-based and second-based integer values in my configuration files. For example, using Redis EXPIRE
(which uses seconds) and setTimeout
in the same project, you get a config file that looks like this:
// config.jsmoduleexports = redis: defaultTtl: 1 stuff: sleepTime: 1000 ;
Which uses which unit?
Instead, with this library, you can have this:
// config.jsconst tsUnit = ;moduleexports = redis: defaultTtl: tsUnit `1s ` stuff: sleepTime: tsUnit `1s ` ;
I find this more explicit.
You could also defer the unit conversing when calling the library, keeping only strings in your configuration file:
// config.jsmoduleexports = redis: defaultTtl: '1s' stuff: sleepTime: '1s' ; // redis.jsconst tsUnit = ;moduleexportssetTtl = async { return await whicheverRedisClient;};
And BAM! unit conversion isn't tied to your configuration anymore, only where it's appropriate.
Note that I don't recommend this method because it may impact performance. You should rather "compile" your strings beforehand, at least for non-variable ones.