I have an array of objects like so, where action
is always either "start" or "stop", and the time
is a UNIX millisecond timestamp (simplified here).
[
{
action: "start",
time: 100,
},
{
action: "stop",
time: 150
},
{
action: "start",
time: 250
},
{
action: "stop",
time: 350
}
]
I need to find out the total amount of elapsed time between each "start" and "stop". In this case, the correct answer would be 150
, because
(150 - 100) + (350 - 250) = 150
It is possible for the array to end in a "start" entry, in which case the difference would be between that time
and Date.now()
.
It has however been ensured that the array is sorted by time, and "start" and "stop" entries will necessarily alternate properly.
How can I go about this?