I have an object array. Every gateType:entry needs to be followed by gateType:exit object.
The problem is some entry object and some exit objects are missing/skipped. I need to create an object array that has the missing objects.
[{
"dateTime": "2016-01-28 15:18:26",
"gateType": "entry",
}, {
"dateTime": "2016-01-28 15:18:27",
"gateType": "exit",
}, {
"dateTime": "2016-01-28 15:19:26",
"gateType": "entry",
}, {
"dateTime": "2016-01-28 15:19:27",
"gateType": "exit",
}, {
"dateTime": "2016-01-28 15:20:26",
"gateType": "entry",
},
// here is the exit object is missing for above
{
"dateTime": "2016-01-28 15:21:25",
"gateType": "entry",
}, {
"dateTime": "2016-01-28 15:21:26",
"gateType": "exit",
}, {
"dateTime": "2016-01-28 15:22:25",
"gateType": "entry",
}, {
"dateTime": "2016-01-28 15:22:26",
"gateType": "exit",
},
// here is the entry object is missing for below
{
"dateTime": "2016-01-28 15:23:26",
"gateType": "exit",
}]
Each entry needs to be followed by exit. But as you can see some entry or exit objects does not exist.
The solution for above example is:
[{
"dateTime": "2016-01-28 15:20:26",
"gateType": "exit",
},{
"dateTime": "2016-01-28 15:23:26",
"gateType": "enty",
}]
My solution was this but it doesn't work like i expected :
function detectMissingOnes(rows) {
var missings = [];
var current = null;
rows.forEach(function (key, index) {
if (index == 0) {
if(key.gateType == "exit"){
var resultDate = moment(key.dateTime);
resultDate = resultDate.subtract(1, 'seconds').format("YYYY-MM-DD HH:mm:ss");
missings.push({
dateTime: resultDate,
gateNumber: key.gateNumber,
gateType: "entry",
personId: key.personId,
fix: 1
});
}
current = key;
return true;
}
if (current.gateType == key.gateType) {
var type = key.gateType == "entry" ? "exit" : "entry";
var resultDate = moment(current.dateTime);
if(type == "entry"){
resultDate = resultDate.subtract(1, 'seconds').format("YYYY-MM-DD HH:mm:ss");
}else {
resultDate = resultDate.add(1, 'seconds').format("YYYY-MM-DD HH:mm:ss");
}
missings.push({
dateTime: resultDate,
gateNumber: current.gateNumber,
gateType: type,
personId: current.personId,
fix: 1
});
}
current = key;
});
return missings;
}
Could you help me to write the algorithm with or without lodash?