I write a lot of timing constants. It’s not really a lot of work, but they all kind of look like this:
const REQUEST_TIMEOUT = 1000 * 20; const COOKIE_EXPIRY_TIME = 1000 * 60 * 60 * 24 * 7; const DEBOUNCE_PERIOD = 500;
The constants are named correctly enough, but I always have to do some quick math whenever I revisit my code. It’s just not very readable! How long is 1000 * 60 * 60 * 12 * 2, really? 🤷
timeproxy is a very tiny, blazingly fast and production ready library (991 bytes gzipped) that lets you write god damn beautiful constants! It uses a fancy “new” ES2015 feature called proxies to make your constants chill af. Don’t worry about the tech, just enjoy the dopeness:
import tp from 'timeproxy'; const REQUEST_TIMEOUT = tp.TWENTY_SECONDS; const COOKIE_EXPIRY_TIME = tp.A_WEEK; const DEBOUNCE_PERIOD = tp.HALF_A_SECOND;
This way, you can express your intent AND the amount of time, without having to deal with math at all. Also, it just reads so much better!
Thanks to some great feedback after this article was published, I’ve added support for using
timeproxy as a tagged template literal as well:
import tp from 'timeproxy'; const REQUEST_TIMEOUT = tp`twenty seconds`; const COOKIE_EXPIRY_TIME = tp`1 week`; const DEBOUNCE_PERIOD = tp`.5 seconds`;
Here’s a few more examples:
import tp from 'timeproxy'; const TIME_UNTIL_NEXT_PUSH = tp.ONE_WEEK_AND_A_DAY; const SHOW_DONT_LEAVE_DELAY = tp.TWELVE_MINUTES_TWO_SECONDS; const WOW = tp.NINE_WEEKS_TWELVE_DAYS_SEVEN_MINUTES_AND_HALF_A_SECOND; // or const TIME_UNTIL_NEXT_PUSH_TS = tp`one week and a day`; const SHOW_DONT_LEAVE_DELAY_TS = tp`12 minutes 2 seconds`; const WOW_TS = tp`9 weeks twelve days and .5 seconds`;
Another feature is relative time. If you want your timestamp to be relative to the current time, prefix with
in or suffix with
import tp from 'timeproxy'; const SESSION_EXPIRES = tp.IN_THIRTY_SECONDS; const OLD_POST_TIMESTAMP = tp`two weeks ago`;
My goal with this library is that it will let you write your constants with natural language. Write what you feel like might make sense, and it will probably just work.
I hope you dig it!
$ npm install timeproxy