I'm seeking help to develop a script that generates JSON data based on specific conditions. As of now, I believe my logic is correct.
Any assistance would be greatly appreciated.
CURRENT ISSUES:
- [resolved]I am unable to determine why the duration consistently returns as 0
- [resolved]Addressing how to set the
max/min
- Solving the issue of managing back-to-back excursions of different types ("hot" ⇒ "cold" or "cold" ⇒ "hot")
This is the expected appearance of each new object
let current_excursion = {
'device_sensor' : '',
'start_at' : [],
'stop_at' : 0,
'duration' : 0,
'type': '',
'max/min':0
}
device_sensor
The sId
where this excursion was detected.
start_at
The timestamp when the temperature first goes out of range in ISO_8601 format
.
stop_at
The timestamp when the temperature returns to the normal range in ISO_8601 format
.
duration The total time in seconds the temperature stayed out of range.
type Either "hot" or "cold", depending on the type of the excursion.
max/min The extreme temperature for the excursion. For a "hot" excursion, this will be the maximum; for a "cold" excursion, it will be the minimum.
A temperature excursion event begins when the temperature goes out of range and ends when it gets back within range. For a "hot" excursion, this occurs when the temperature exceeds 8°C, and for a "cold" excursion, it happens when the temperature falls below 2°C. If two excursions of different types occur consecutively ("hot" ⇒ "cold" or "cold" ⇒ "hot"), consider the midpoint between the timestamps as the end of the first excursion and the start of the second one.
If an excursion is ongoing at the final temperature reading, conclude the excursion at that point (with a duration of 0).
Here is the link to access the test data: Test Case Data
Below is what I have written so far:
const tempTypeTernary = (num) =>{
if(num < 2){
return 'cold'
} else if(num > 8){
return 'hot'
}
}
const excursion_duration = (x,y) =>{
let start = new Date(x) / 1000
let end = new Date(y) / 1000
return end - start
}
const reset_excursion = (obj) => {
Object.keys(obj).map(key => {
if (obj[key] instanceof Array) obj[key] = []
else obj[key] = ''
})
}
const list_excursion = (array) =>{
let result = [];
let max_min_excursion = 0;
let current_excursion = {
'device_sensor' : '',
'start_at' : [],
'stop_at' : 0,
'duration' : 0,
'type': '',
'max/min':0
}
for(let k = 0; k < array.length;k++){
if( array[k]['tmp'] < 2 || array[k]['tmp'] > 8){
current_excursion['device_sensor'] = array[k]['sId'];
current_excursion['start_at'] = [new Date(array[k]['time']).toISOString(),array[k]['time']];
current_excursion['type'] = tempTypeTernary(array[k]['tmp']);
if( array[k]['tmp'] > 2 || array[k]['tmp'] < 8){
current_excursion['stop_at'] = new Date(array[k]['time']).toISOString();
current_excursion['duration'] = excursion_duration(current_excursion['start_at'][1],array[k]['time'])
}
result.push(current_excursion)
reset_excursion(current_excursion)
}
}
return result
}
list_excursion(json)