xp-types
A pack to handle javascript data types
Install
npm i xp-types --save
Usage
import { string } from 'xp-types'
let str = 'I am 韩小平'
console.log(str.length)
let len = string.len(str)
console.log(len)
API
object
object.deepCopy(obj)
let obj = { a: 1 }
let obj2 = object.deepCopy(obj)
obj2.a = 2
console.log(obj)
console.log(obj2)
object.objectify(obj, keys)
- if obj[key] is
undefined, null, 0, etc.
, change it to {}
let obj = {}
console.log(obj.a)
object.objectify(obj, ['a'])
console.log(obj.a)
array
array.fastArr(num, from)
- fast get an array of ordered numbers
let arr1 = array.fastArr(5)
let arr2 = array.fastArr(5, 6)
array.unique(arr)
- remove repeated values, only work for primitive types
let arr = [1, 2, 3, 2]
let arr2 = array.unique(arr)
array.order(arr, reverse)
- order array elements, will effect the array, no return value
let arr = [1, 4, 3, 2]
let arr2 = [2, 1, 3, 4]
array.order(arr)
console.log(arr)
array.order(arr2, true)
console.log(arr2)
array.arraify(arr)
- change
undefined, null, 0, etc.
to []
let arr = null
let ret = array.arraify(arr)
console.log(ret)
string
string.len(str)
- get the real length of a string(1 Chinese charactor equals to 2 English charactors).
let str = 'I am 韩小平'
let len = string.len(str)
console.log(len)
string.ellipsis(str, maxLen, suffix)
- cut the string if it is more than certain length, and use suffix string to replace the rest.
let str = 'this is a note'
let newStr = string.ellipsis(str, 7)
console.log(newStr)
string.stringify(str)
- change
undefined, null, 0, etc.
to ''
let str
let ret = string.stringify(str)
console.log(ret)
number
number.numberify(num)
let num
let ret = number.numberify(num)
console.log(ret)
url
url.query(name)
- get url query value, if name isn't set, will return the query object
let url = 'http://www.example.com?name=xp&test=1#token=abc&filter=2'
url.query()
url.query('name')
url.hash(name)
- get url hash value, if name isn't set, will return the hash object
let url = 'http://www.example.com?name=xp&test=1#token=abc&filter=2'
url.hash()
url.hash('filter')
url.hostname()
let url = 'http://www.example.com?name=xp&test=1#token=abc&filter=2'
url.hostname()
url.domain()
let url = 'http://www.example.com?name=xp&test=1#token=abc&filter=2'
url.domain()
url.sub()
let url = 'http://www.example.com?name=xp&test=1#token=abc&filter=2'
url.sub()
date
date.format(time, fmt)
let time = new Date()
date.format(time, 'YYYY-MM-DD')
date.duration
- convert seconds to Chinese string
let time = 615
date.duration(time)
date.ago
- convert passed time to Chinese string
let time = 3815
date.ago(time)