xp-types
A pack to handle javascript data types
Install
npm i xp-types --save
Usage
// let string = require('xp-types').string let str = 'I am 韩小平'console // 8 let len = stringconsole // 11
API
object
object.deepCopy(obj)
- deep copy object
let obj = a: 1 let obj2 = objectobj2a = 2console // { a: 1 }console // { a: 2 }
object.objectify(obj, keys)
- if obj[key] is
undefined, null, 0, etc.
, change it to{}
let obj = {}console // undefinedobjectconsole // {}
array
array.fastArr(num, from)
- fast get an array of ordered numbers
let arr1 = array // [1, 2, 3, 4, 5]let arr2 = array // [6, 7, 8, 9, 10]
array.unique(arr)
- remove repeated values, only work for primitive types
let arr = 1 2 3 2let arr2 = array // [1, 2, 3]
array.order(arr, reverse)
- order array elements, will effect the array, no return value
let arr = 1 4 3 2let arr2 = 2 1 3 4arrayconsole // [1, 2, 3, 4] arrayconsole // [4, 3, 2, 1]
array.arraify(arr)
- change
undefined, null, 0, etc.
to[]
let arr = nulllet ret = arrayconsole // []
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 = stringconsole // 11
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 = stringconsole // this is...
string.stringify(str)
- change
undefined, null, 0, etc.
to''
let strlet ret = stringconsole // ''
number
number.numberify(num)
let numlet ret = numberconsole // 0
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 // { name: 'xp', test: 1 }url // xp
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'urlhash // { token: 'abc', filter: 2 }urlhash'filter' // 2
url.hostname()
- get the hostname
let url = 'http://www.example.com?name=xp&test=1#token=abc&filter=2'urlhostname // www.example.com
url.domain()
- get the domain
let url = 'http://www.example.com?name=xp&test=1#token=abc&filter=2'url // example.com
url.sub()
- get the sub
let url = 'http://www.example.com?name=xp&test=1#token=abc&filter=2'url // www
date
date.format(time, fmt)
- get formatted time
let time = date // 2017-05-31
date.duration
- convert seconds to Chinese string
let time = 615date // 10分15秒
date.ago
- convert passed time to Chinese string
let time = 3815date // 1小时前