From be0297fc84be93e30f3a06a6deeb918e60683cb0 Mon Sep 17 00:00:00 2001 From: euvl Date: Wed, 12 Jul 2017 16:45:43 +0100 Subject: [PATCH] Added a module to tokenize strings of format number_suffix, e.g. 100px --- src/Modal.vue | 6 ++-- src/floatStringParser.js | 73 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 src/floatStringParser.js diff --git a/src/Modal.vue b/src/Modal.vue index ca13252..9f96d49 100644 --- a/src/Modal.vue +++ b/src/Modal.vue @@ -96,7 +96,8 @@ default: 600, validator (value) { if (typeof value === 'string') { - return value.charAt(value.length-1) === '%' && !isNaN(parseFloat(value)) + return value.charAt(value.length-1) === '%' + && !isNaN(parseFloat(value)) } if (typeof value === 'number') { @@ -109,7 +110,8 @@ default: 300, validator (value) { if (typeof value === 'string') { - return value === 'auto' || (value.charAt(value.length-1) === '%' && !isNaN(parseFloat(value))) + return (value.charAt(value.length-1) === '%' + && !isNaN(parseFloat(value))) } if (typeof value === 'number') { diff --git a/src/floatStringParser.js b/src/floatStringParser.js new file mode 100644 index 0000000..a34793b --- /dev/null +++ b/src/floatStringParser.js @@ -0,0 +1,73 @@ +// Parses string with float number and suffix: +// "0.001" => { type: "px", value: 0.001 } +// "0.001px" => { type: "px", value: 0.001 } +// "0.1%" => { type: "px", value: 0.1 } +// "foo" => { type: "", value: "foo" } + +var floatRegexp = '[-+]?[0-9]*\.?[0-9]+' + +var types = [ + { + name: 'px', + regexp: new RegExp(`^${floatRegexp}px\$`) + }, + { + name: '%', + regexp: new RegExp(`^${floatRegexp}%\$`) + }, + // Fallback option: + // If no suffix specified, assign to px + { + name: 'px', + regexp: new RegExp(`^${floatRegexp}\$`) + } +] + +var getType = (value) => { + for (var i = 0; i < types.length; i++) { + let type = types[i] + if (type.regexp.test(value)) { + return { + type: type.name, + value: parseFloat(value) + } + } + } + + return { + type: '', + value: value + } +} + +var parse = (value) => { + switch (typeof value) { + case 'number': + return { type: 'px', value } + case 'string': + return getType(value) + default: + return { type: '', value } + } +} + +export default parse + +/// tests +/* +console.log(parse(10)) +console.log(parse(10.10)) +console.log(parse(-10)) + +console.log(parse('5%')) +console.log(parse('-5%')) +console.log(parse('5.123%')) + +console.log(parse('5px')) +console.log(parse('-5px')) +console.log(parse('5.123px')) + +console.log(parse("adasd%")) +console.log(parse("")) +console.log(parse("+2-3px")) // fails +*/ \ No newline at end of file