Skip to content

Instantly share code, notes, and snippets.

@mattparker
Forked from lsmith/gist:5417052
Last active December 16, 2015 10:29
Show Gist options
  • Save mattparker/5420634 to your computer and use it in GitHub Desktop.
Save mattparker/5420634 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') {
// use the existing one or build it if needed
parser = parse._parser || buildParser(config.prefix, config.suffix, config.thousandsSeparator, config.decimalSeparator);
// Put the parser function as a protected property of the
// function?
parse._parser = parser;
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