Skip to content

Instantly share code, notes, and snippets.

@lsmith
Created April 18, 2013 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lsmith/5417052 to your computer and use it in GitHub Desktop.
Save lsmith/5417052 to your computer and use it in GitHub Desktop.
var buildParser = Y.cached(function (prefix, suffix, separator, decimal) {
var regexBits = []
regex;
if (prefix) {
regexBits.push('^' + prefix.replace(safeRegExp, '\\$1'));
}
if (suffix) {
regexBits.push(suffix.replace(safeRegExp, '\\$1') + '$');
}
if (separator) {
regexBits.push(separator.replace(safeRegExp, '\\$1') + '(?=\\d)');
}
regex = new RegExp('(?:' + regexBits.join('|') + ')', 'g');
if (decimal === '.') {
decimal = null;
}
return function (val) {
val = val.replace(regex, '');
return decimal ? val.replace(decimal, '.') : val;
}
});
parse: function(data, config) {
var parser;
if (config && typeof data === 'string') {
parser = buildParser(config.prefix, config.suffix, config.thousandsSeparator, config.decimalSeparator);
data = parser(data);
}
if (data !== null && data !== "") {
data = +data;
// catch NaN and ±Infinity
if (!isFinite(data)) {
data = null;
}
} else {
data = null;
}
// on the same line to get stripped for raw/min.js by build system
if (data === null) { Y.log("Could not parse data to type Number", "warn", "number"); }
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment