Create internal methods with regexp test

- Make it more easily readable and add unit tests
This commit is contained in:
Jean-Baptiste Bellet
2021-06-11 10:40:02 +02:00
parent 178c0a441b
commit db8f8a2675
2 changed files with 28 additions and 4 deletions

View File

@@ -7,12 +7,10 @@ angular.module("admin.utils").factory "PriceParser", ->
thousands_separator = I18n.toCurrency(1000, {precision: 1, unit: ''}).substring(1,2)
# Replace comma used as a decimal separator and remplace by "."
if (price.match(/^[0-9]*(,{1})[0-9]{1,2}$/g))
price = price.replace(",", ".")
price = this.replaceCommaByFinalPoint(price)
# Remove configured thousands separator if it is actually a thousands separator
if (new RegExp("^([0-9]*(" + thousands_separator + "{1})[0-9]{3}[0-9\.,]*)*$", "g").test(price))
price = price.replaceAll(thousands_separator, '')
price = this.removeThousandsSeparator(price, thousands_separator)
if (decimal_separator == ",")
price = price.replace(",", ".")
@@ -22,3 +20,12 @@ angular.module("admin.utils").factory "PriceParser", ->
return null if isNaN(price)
return price
replaceCommaByFinalPoint : (price) =>
if price.match(/^[0-9]*(,{1})[0-9]{1,2}$/g) then price.replace(",", ".") else price
removeThousandsSeparator : (price, thousands_separator) =>
if (new RegExp("^([0-9]*(" + thousands_separator + "{1})[0-9]{3}[0-9\.,]*)*$", "g").test(price))
price.replaceAll(thousands_separator, '')
else
price

View File

@@ -6,6 +6,23 @@ describe "PriceParser service", ->
inject (PriceParser) ->
priceParser = PriceParser
describe "test internal method with Regexp", ->
describe "test replaceCommaByFinalPoint() method", ->
it "handle the default case (with two numbers after comma)", ->
expect(priceParser.replaceCommaByFinalPoint("1,00")).toEqual "1.00"
it "doesn't confuse with thousands separator", ->
expect(priceParser.replaceCommaByFinalPoint("1,000")).toEqual "1,000"
it "handle also when there is only one number after the decimal separator", ->
expect(priceParser.replaceCommaByFinalPoint("1,0")).toEqual "1.0"
describe "test removeThousandsSeparator() method", ->
it "handle the default case", ->
expect(priceParser.removeThousandsSeparator("1,000", ",")).toEqual "1000"
expect(priceParser.removeThousandsSeparator("1,000,000", ",")).toEqual "1000000"
it "handle the case with decimal separator", ->
expect(priceParser.removeThousandsSeparator("1,000,000.00", ",")).toEqual "1000000.00"
it "handle the case when it is actually a decimal separator (and not a thousands one)", ->
expect(priceParser.removeThousandsSeparator("1,00", ",")).toEqual "1,00"
describe "with point as decimal separator and comma as thousands separator for I18n service", ->
beforeEach ->