JSFiddle - React, Tailwind, and code Playground
by pcejas
JavaScript
function decodeFilename(containerDateTime, filename) {
// Remove the file extension
const name = filename.split('.')[0];
// Regex to match the pattern
const regex = /^(\w{4})(?:\((\w+)\))?(.+?)(?:H)?$/;
const match = name.match(regex);
if (!match) {
throw new Error("Filename does not match the expected format.");
}
const timeCodePart = match[1];
const timeCorPart = match[2] ? match[2] : "0";
const stationCodePart = match[3];
// Convert hex time code to seconds
const timeCodeSeconds = parseInt(timeCodePart, 16) * 2;
const timeSpan = timeCodeSeconds * 1000; // convert to milliseconds
// Combine the time with the start of the day
const timeCode = new Date(containerDateTime.getTime() + timeSpan);
// Convert TimeCor to a double representing tenths of a second
const timeCor = parseFloat(timeCorPart) / 10.0;
// Convert StationCode from hex to decimal
const stationCode = parseInt(stationCodePart, 16);
return {
TimeCode: timeCode,
TimeCor: timeCor,
StationCode: stationCode.toString()
};
}
// Example usage
const containerDateTime = new Date(2024, 6, 17); // July 17, 2024 (months are 0-indexed)
const filename = "1234(56)7890H.wav";
const recordingInfo = decodeFilename(containerDateTime, filename);
console.log(recordingInfo);