工作中碰到了一些可以和業(yè)務(wù)剝離并封裝為工具函數(shù)的邏輯猿棉,按照自己的想法寫了一下記錄在這里磅叛,以后碰到新的會(huì)在這里追加更新。讀者朋友如果有更好的實(shí)現(xiàn)或者任何建議萨赁,非常歡迎你的指教和關(guān)懷弊琴!
判斷是否為老版本
偶爾會(huì)碰到要對(duì)APP老版本做兼容處理的情形。
function isOldVersion (boundry, current) {
const boundryArr = boundry.split('.')
const currentArr = current.split('.')
for (let i = 0; i < 3; i++) {
const bound = Number(boundryArr[i])
const curr = Number(currentArr[i])
if (cuur < bound) {
return true
} else if (curr > bound) {
return false
}
}
return false
}
input | output |
---|---|
isOldVersion('5.1.0', '4.2.34') |
true |
isOldVersion('5.1.0', '11.3.22') |
false |
isOldVersion('5.1.0', '5.1.0') |
false |
價(jià)格格式化
有時(shí)要給價(jià)格加逗號(hào)杖爽,但服務(wù)端返回的數(shù)據(jù)格式各一敲董。
function formatPrice (price) {
if (!price) {
return 0
}
if (/,/.test(price)) {
return price
}
price = String(price)
const intPrice = price.match(/\d+/)[0]
const HOLDER = 'HOLDER'
const holder = price.replace(intPrice, HOLDER)
const intPriceArr = intPrice.split('').reverse()
let res = ''
intPriceArr.forEach((item, index) => {
if (index % 3 === 0 && index) {
res = item + ',' + res
} else {
res = item + res
}
})
return holder.replace(HOLDER, res)
}
還可以用 Number
的 toLocaleString
方法替換手動(dòng)加逗號(hào)的過程:
function formatPrice (value) {
if (!value) {
return 0
}
if (/,/.test(value)) {
return value
}
value = String(value)
const reg = /\d+\.?\d*/
const HOLDER = 'HOLDER'
const price = value.match(reg)[0]
const holder = value.replace(price, HOLDER)
value = holder.replace(HOLDER, Number(price).toLocaleString())
return value
}
input | output |
---|---|
formatPrice(2689999) |
2,689,999 |
formatPrice('2689999') |
2,689,999 |
formatPrice('2689999元') |
2,689,999元 |
formatPrice('裸車價(jià):¥2689999') |
裸車價(jià):¥2,689,999 |
formatPrice('優(yōu)惠:2689999元') |
優(yōu)惠:2,689,999元 |
formatPrice('到手價(jià):2689999.99元') |
到手價(jià):2,689,999.99元 |
formatPrice('2,689,999') |
2,689,999 |
formatPrice('') |
0 |
formatPrice() |
0 |