一些工具函数

作者: 边城少年_ | 来源:发表于2018-12-11 21:34 被阅读64次

工作中碰到了一些可以和业务剥离并封装为工具函数的逻辑,按照自己的想法写了一下记录在这里,以后碰到新的会在这里追加更新。读者朋友如果有更好的实现或者任何建议,非常欢迎你的指教和关怀!

判断是否为老版本

偶尔会碰到要对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

价格格式化

有时要给价格加逗号,但服务端返回的数据格式各一。

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)
}

还可以用 NumbertoLocaleString 方法替换手动加逗号的过程:

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('裸车价:¥2689999') 裸车价:¥2,689,999
formatPrice('优惠:2689999元') 优惠:2,689,999元
formatPrice('到手价:2689999.99元') 到手价:2,689,999.99元
formatPrice('2,689,999') 2,689,999
formatPrice('') 0
formatPrice() 0

相关文章

  • 一些工具函数

    工作中碰到了一些可以和业务剥离并封装为工具函数的逻辑,按照自己的想法写了一下记录在这里,以后碰到新的会在这里追加更...

  • 2018-05-10 第七周

    本周任务:LycorisNet的工具类(utils类)设计 工具类需要包含神经网络必备的一些函数,诸如各种激活函数...

  • 算法工具

    functools管理函数的工具 functools模块提供了一些工具来调整或扩展函数和其他可回调对象,而不必完全...

  • 前端一些工具函数

  • Kotlin学习之Set常用集合工具函数

    Kotlin学习之Set常用集合工具函数 Kotlin中定义了很多工具函数,用来创建不同类型的Set,下面是一些常...

  • 解放你双手的JS工具函数大全(满满的干货)

    作者:@Eno Yao 在平时的项目开发中不可避免要写一些工具函数,辅助我们进行开发,而很多工具函数其实可以运用到...

  • VBA操作Excel的一个简单网络应用

    前言: Excel基本是用来处理表单数据的,里面自带一些工具和函数,熟练运用工具和函数可以让Excel变得比较高效...

  • 2019-11-28

    AM: 1.函数的概念及作用 函数:就是一个工具,完成某个功能的一段代码块 系统函数:js自带的一些函数 2.函数...

  • gobox中的常用工具包gomisc

    有一些常用的工具函数,我们把它们放到gomisc这个包中。 工具介绍 Slice中的值Unique 示例: 输出:...

  • 原生js实现promise部分功能

    Emitter 工具函数 Promise函数 DEMO

网友评论

本文标题:一些工具函数

本文链接:https://www.haomeiwen.com/subject/efkyhqtx.html