I have to recreate some logic from Kusto query language in JS and I’m struggling with duration division. How can I get quotient from two durations, like this :
One can divide two timespan values to get their quotient. For example, 1d / 5h gives 4.8. This gives one the ability to express any timespan value as a multiple of another timespan value. For example, to express an hour in seconds, simply divide 1h by 1s: 1h / 1s (with the obvious result, 3600).
(taken from https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/datetime-timespan-arithmetic)
I’m using date-fns, but I’m flexible with libraries.
Advertisement
Answer
You can simply define constants. For example, if the smallest unit you are going to use is 1 seconds, then you can put:
const S = 1, M = 60, H = M * 60, D = H * 24, W = D * 7;
Now terms like 1s
cannot magically become a valid syntax in JavaScript, but expressions like (2 * D) / (10 * H)
can work just fine.
(edited the answer to use uppercase for constants as it’s a common convention)