Last active
August 29, 2015 14:06
-
-
Save joshblack/3b5ade0b70f8364d53c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var timeSyntaxRules = { | |
1: function (time) { | |
// Check to see if first digit is not 1, then preface it with zero | |
var pattern = /[2-9]/; | |
if (time.match(pattern)) { | |
return "0" + time; | |
} | |
return time; | |
}, | |
3: function (time) { | |
if (time[2] === ':') { | |
return time.substring(0, 2); | |
} | |
return time | |
}, | |
4: function (time) { | |
// Edit time string if user is trying to input a 1:XX style time | |
if (time[3] === 'A' || time[3] === 'P') { | |
return "0" + time.substring(0, 3) + time.substring(3); | |
} | |
return time; | |
}, | |
5: function (time) { | |
if (time[4] === ' ') { | |
return time.substring(0, 4); | |
} | |
return time; | |
}, | |
/** | |
* Insert a given value into a position in a string | |
* | |
* @param {string} str The string you want manipulated | |
* @param {int} pos The position in the string you want the value inserted at | |
* @param {string} val The value you want inserted at that position | |
* @return {return} An updated string with the value inserted | |
*/ | |
insert: function (str, pos, val) { | |
return [str.substring(0, pos) + val + str.substring(pos)].join(''); | |
} | |
}; | |
/** | |
* Formats the given time according to our timepicker syntax rules | |
* @param {string} time The time we want to format | |
* @return {string} The formatted string | |
*/ | |
function formatTime(time) { | |
// Strip our time of any backslashes that would escape our RegEx sequence | |
time = time.replace(/\\/g, ''); | |
// Split up the string into individual characters | |
var letters = time.toUpperCase().split(''); | |
// Format the string from the beginning in order to ensure each syntax rule is enforced | |
return letters.reduce(function (prev, curr) { | |
return applySyntaxRules(prev + curr, timeSyntaxRules); | |
}, ""); | |
}; | |
/** | |
* Apply a given set of syntax rules to a string | |
* @param {string} str The string that's going to be formatted | |
* @param {object} rules A dictionary object applied to the given string | |
* @return {string} The formatted string | |
*/ | |
function applySyntaxRules(str, rules) { | |
// Apply the syntax rule if we have one for the given time length | |
if (rules[str.length]) { | |
str = rules[str.length](str); | |
} | |
return str; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment