Skip to content

Instantly share code, notes, and snippets.

@jmcook1186
Created December 7, 2023 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmcook1186/05215df352b4b8418fc93fb7d9f0d7ee to your computer and use it in GitHub Desktop.
Save jmcook1186/05215df352b4b8418fc93fb7d9f0d7ee to your computer and use it in GitHub Desktop.
dummy-time-sync
// some input data with gaps in the record
const inputs = [{ timestamp: '2023-07-06T00:00', carbon: 10, energy: 30, duration: 10 },
{ timestamp: '2023-07-06T00:10', carbon: 10, energy: 30, duration: 10 },
{ timestamp: '2023-07-06T00:30', carbon: 10, energy: 30, duration: 5 },
{ timestamp: '2023-07-06T00:50', carbon: 10, energy: 30, duration: 20 }
]
const startTime = '2023-07-06T00:00'
const interval = 60
const endTime = '2023-07-06T10:00'
type InData = { timestamp: string, carbon: number, energy: number, duration: number }
var newInputs: InData[] = []
//todo: granularity is user defined
// convert to entry per second, shift sub-second variations to whole seconds
inputs.forEach(input => {
input.timestamp = Math.floor(new Date(input.timestamp).getTime() / 1000).toString()
let energyPerTime = input.energy / input.duration
let carbonPerTime = input.carbon / input.duration
for (let i = 0; i < input.duration; i++) {
newInputs.push({ timestamp: ((parseFloat(input.timestamp) - (parseFloat(input.timestamp) % 1000)) + (i * 1000)).toString(), carbon: carbonPerTime, energy: energyPerTime, duration: 1 })
}
})
// fill in missing data
const unixStartTime = Math.floor(new Date(startTime).getTime() / 1000)
const unixEndTime = Math.floor(new Date(endTime).getTime() / 1000)
var missingFlag = false
for (let i = unixStartTime; i < unixEndTime; i += 1000) {
newInputs.map(input => {
if (!(Object.values(input).includes(i.toString()))) {
missingFlag = true
}
})
if (missingFlag) {
newInputs.push({ timestamp: i.toString(), energy: 0, carbon: 0, duration: 1 })
}
missingFlag = false
}
// sort data into time order by UNX timestamp
newInputs.sort((a, b) => parseFloat(a.timestamp) - parseFloat(b.timestamp)); // b - a for reverse sort
// now we have contionuous 1 second data
// now sum in batches of size == timespan
// console.log(unixStartTime)
// console.log(unixEndTime)
// console.log(unixEndTime - unixStartTime)
console.log(newInputs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment