Skip to content

Instantly share code, notes, and snippets.

@ryankinal
Created February 7, 2012 16:30
Show Gist options
  • Save ryankinal/1760561 to your computer and use it in GitHub Desktop.
Save ryankinal/1760561 to your computer and use it in GitHub Desktop.
time parser for SCORM-formatted times
/*
Strings of format PNYNMNDTNHNMNS where N is a number.
What the number represents is determined by the letter
immediately following the number.
Y: years
M: before the "T", months; after the "T", minutes
D: days
H: hours
S: seconds
*/
var timeParser = (function() {
var result = {
years: 0,
months: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
toSeconds: function()
{
return this.years * 31556926 +
this.months * 2629743.83 +
this.days * 86400 +
this.hours * 3600 +
this.minutes * 60 +
this.seconds;
}
},
numerals = /[\d\.]/,
letters = /[YMDTHMS]/,
value = '',
time = false,
tokens = [];
var numeral = function()
{
value += tokens.shift();
return parseHelper();
}
/**
Either switches from "day" mode
to "time" mode, or determines
what to do with the current value
**/
var indicator = function()
{
var token = tokens.shift(),
val = parseFloat(value);
switch (token)
{
case 'T': // Switch state to "time" mode
time = true;
break;
case 'Y':
result.years = val
break;
case 'M':
if (time)
{
result.minutes = val;
}
else
{
result.months = val;
}
break;
case 'D':
result.days = val;
break;
case 'H':
result.hours = val;
break;
case 'S':
result.seconds = parseFloat(value);
break;
}
value = '';
if (tokens.length > 0)
{
return parseHelper();
}
else
{
return result;
}
}
/**
determine what the current token
represents, and call the appropriate
function.
letter - a state indicator
numeral - a value
**/
var parseHelper = function()
{
if (letters.test(tokens[0]))
{
return indicator();
}
else if (numerals.test(tokens[0]))
{
return numeral();
}
else
{
return false;
}
}
/**
tokenize the string,
reset the result object,
and start the actual parse
via parseHelper
**/
var parse = function(timeString)
{
tokens = timeString.split('');
time = false;
var token = tokens.shift();
result.years = 0;
result.months = 0;
result.days = 0;
result.hours = 0;
result.minutes = 0;
result.seconds = 0;
if (token === 'P')
{
return parseHelper();
}
else
{
return false;
}
}
return {
parse: parse
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment