ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] > [官方 demo](https://licia.liriliri.io/docs.html) ## 安装 ``` npm i licia --save ``` ### 在小程序中使用 ``` npm i miniprogram-licia --save ``` 2、点击开发者工具中的菜单栏:`工具 --> 构建 npm` 3、直接在代码中引入使用 ``` const licia = require('miniprogram-licia'); licia.md5('licia'); // -> 'e59f337d85e9a467f1783fab282a41d0' licia.safeGet({a: {b: 1}}, 'a.b'); // -> 1 ``` ### 生成定制化 util.js 1、访问[https://licia.liriliri.io/builder.html](https://licia.liriliri.io/builder.html) 2、输入需要的模块名,点击生成下载 util.js。 3、将生成的工具库拷贝到小程序项目任意目录下然后直接引入使用。 ``` const util = require('../lib/util'); util.wx.getStorage({ key: 'test' }).then(res => console.log(res.data)); ``` ## 数组 ### chunk 切割数组 ``` chunk([1, 2, 3, 4], 2); // -> [[1, 2], [3, 4]] chunk([1, 2, 3, 4], 3); // -> [[1, 2, 3], [4]] chunk([1, 2, 3, 4]); // -> [[1], [2], [3], [4]] ``` ### Lru (可设置长度)值的存取清空 ``` var QuickLru = require("licia/QuickLru"); const cache = new QuickLru(50); // 一共存储的大小,空则无限制 cache.set('test', 'licia'); cache.get('test'); // -> 'licia' //其他方法 has,remove,clear ``` ### LinkedList 队列操作 ``` var LinkedList = require("licia/LinkedList"); var linkedList = new LinkedList(); linkedList.push({name:"2"}); linkedList.push({name:"3"}); linkedList.push(5); linkedList.unshift(10) linkedList.head.value;//10 linkedList.size;//2 linkedList.tail;//首个节点 linkedList.shift();//10 linkedList.tail.prev.value;//{ name: '3' } linkedList.pop(); //5 linkedList.forEach(function (p) { console.log(p);//{ name: '2' } }) linkedList.toArr(); //[ { name: '2' }, { name: '3' } ] ``` ### combine 合并两个素组分为别 key ,value ``` combine(['a', 'b', 'c'], [1, 2, 3]); // -> {a: 1, b: 2, c: 3} ``` ### concat 连接两个数组 `concat([1, 2], [3], [4, 5]); // -> [1, 2, 3, 4, 5]` ### contain 数组,对象,字符串是否包含 ``` contain([1, 2, 3], 1); // -> true contain({a: 1, b: 2}, 1); // -> true contain('abc', 'a'); // -> true ``` ### difference ``` difference([3, 2, 1], [4, 2]); // -> [3, 1] ``` ### flatten 多数组扁平化 ``` flatten(['a', ['b', ['c']], 'd', ['e']]); // -> ['a', 'b', 'c', 'd', 'e'] ``` ### randomItem 从数组中随机取 ``` randomItem([1, 2, 3]); // -> 2 ``` ### slice ``` slice([1, 2, 3, 4], 1, 2); // -> [2] ``` ## Number ### max 最大整数 ``` max(2.3, 1, 4.5, 2); // 4.5 ``` ### min ``` min(2.3, 1, 4.5, 2); // 1 ``` ### random 随机整数阿萨德 ``` random(1, 5); // -> an integer between 0 and 5 random(1,5,true); // 4.341859521783398 random(1.2, 5.2, true); /// -> a floating-point number between 1.2 and 5.2 ``` ### range ``` range(5); // -> [0, 1, 2, 3, 4] range(0, 5, 2) // -> [0, 2, 4] ``` ## 字符串 ### randomId 随机字符串 ``` randomId(); // -> 'oKpy4HwU8E6IvU5I03gyQ' randomId(5); // -> 'sM6E9' randomId(5, 'abc'); // -> 'cbbcb' ``` ### camelCase 转驼峰写法 ``` var camelCase = require("licia/camelCase"); camelCase('foo-bar'); // -> fooBar camelCase('foo bar'); // -> fooBar camelCase('foo_bar'); // -> fooBar camelCase('foo.bar'); // -> fooBar ``` ### fileSize 整数转文件大小 ``` fileSize(5); // -> '5' fileSize(1500); // -> '1.46K' fileSize(1500000); // -> '1.43M' fileSize(1500000000); // -> '1.4G' fileSize(1500000000000); // -> '1.36T' ``` ### ini 读取 ini 配置文件/对象转 ini 文件 ``` var ini = require("licia/ini"); const config = ini.parse(` ; This is a comment library = licia [user.info] name = surunzi alias[] = redhoodsu alias[] = red `); // -> {library: 'licia', user: {info: {name: 'surunzi', alias: ['redhoodsu', 'red']}}} console.log(ini.stringify(config)); //对象转 ini 参数 ``` ### trim ### rtrim ### ltrim ``` ltrim(' abc '); // -> 'abc ' ltrim('_abc_', '_'); // -> 'abc_' ltrim('_abc_', ['a', '_']); // -> 'bc_' ``` ### splitPath ``` splitPath('f:/foo/bar.txt'); // -> {dir: 'f:/foo/', name: 'bar.txt', ext: '.txt'} splitPath('/home/foo/bar.txt'); // -> {dir: '/home/foo/', name: 'bar.txt', ext: '.txt'} ``` ### repeat ``` repeat('a', 3); // -> 'aaa' repeat('ab', 2); // -> 'abab' repeat('*', 0); // -> ``` ### getUrlParam 获取 url 中的指定参数 ``` getUrlParam('test', 'http://example.com/?test=true'); // -> 'true' ``` ### query obj->url url->obj ``` query.parse('foo=bar&eruda=true'); // -> {foo: 'bar', eruda: 'true'} query.stringify({foo: 'bar', eruda: 'true'}); // -> 'foo=bar&eruda=true' query.parse('name=eruda&name=eustia'); // -> {name: ['eruda', 'eustia']} ``` ### stripHtmlTag ``` stripHtmlTag('<p>Hello</p>'); // -> 'Hello' ``` ### uuid ``` uuid(); // -> '53ce0497-6554-49e9-8d79-347406d2a88b' ``` ## 加密/uuid ### base64 ``` base64.encode([168, 174, 155, 255]); // -> 'qK6b/w==' base64.decode('qK6b/w=='); // -> [168, 174, 155, 255] ``` ### md5 ``` md5('licia'); // -> 'e59f337d85e9a467f1783fab282a41d0' ``` ### rc4 ``` rc4.encrypt('licia', 'Hello world'); // -> 'j9y2VpSfR3AdNN8=' rc4.decrypt('licia', 'j9y2VpSfR3AdNN8='); // -> 'Hello world' ``` ### vlq ``` vlq.encode(123); // -> '2H' vlq.encode([123, 456, 789]); // -> '2HwcqxB' vlq.decode('2H'); // -> [123] vlq.decode('2HwcqxB'); // -> [123, 456, 789] ``` ## 网路/浏览器/服务器 ### ajax > [doc](https://licia.liriliri.io/docs.html#ajax) ``` ajax({ url: 'http://example.com', data: {test: 'true'}, error() {}, success(data) { // ... }, dataType: 'json' }); ajax.get('http://example.com', {}, function (data) { // ... }); ``` ### jsonp ``` jsonp({ url: 'http://example.com', data: {test: 'true'}, success: function (data) { // ... }, param:"callback" }); ``` ## copy 复制到剪切板 ``` copy('text', function (err) { // Handle errors. }); ``` ### cookie ``` cookie.set('a', '1', {path: '/'}); cookie.get('a'); // -> '1' cookie.remove('a'); ``` ## json/对象 ### JsonTransformer json 转 对象进行过滤等操作 ``` var JsonTransformer = require("licia/JsonTransformer"); var data = new JsonTransformer({ books: [{ title: 'Book 1', price: 5 }, { title: 'Book 2', price: 10 },{ title: 'Book 3', price: 11 }], author: { lastname: 'Su', firstname: 'RedHood' } }); data.filter('books', function (book) { return book.price > 5 }); /** * { books: [ { title: 'Book 2', price: 10 } ], author: { lastname: 'Su', firstname: 'RedHood' }} */ console.log(data.get()); // data.compute('author', function (author) { return author.firstname +"_"+ author.lastname }); // console.log(data.get()); //{ books: [ { title: 'Book 2', price: 10 } ], author: 'RedHood_Su' } data.set('count', data.get('books').length); console.log(data.get());// ; // -> {books: [{title: 'Book 2', price: 10}], author: 'RedHoodSu', count: 1} data.remove("author.lastname") var newData = data.map("books","new_books",function (p,index) { return p.title+":"+p.price+"元" }) /** * { books: [ { title: 'Book 2', price: 10 }, { title: 'Book 3', price: 11 } ], author: { firstname: 'RedHood' }, count: 2, new_books: [ 'Book 2:10元', 'Book 3:11元' ] } */ console.log(newData.get()); ``` ### each 遍历对象的 key/value ``` each({'a': 1, 'b': 2}, function (val, key) {}); ``` ### mapObj ``` mapObj({a: 1, b: 2}, function (val, key) { return val + 1 }); // -> {a: 2, b: 3} ``` ### extend 合并对象 ``` extend({name: 'RedHood'}, {age: 24}); // -> {name: 'RedHood', age: 24} ``` ### extendDeep 深度合并对象 ``` extendDeep({ name: 'RedHood', family: { mother: 'Jane', father: 'Jack' } }, { family: { brother: 'Bruce' } }); // -> {name: 'RedHood', family: {mother: 'Jane', father: 'Jack', brother: 'Bruce'}} T ``` ### fuzzySearch 搜索对象/数组 ``` var fuzzySearch = require("licia/fuzzySearch"); fuzzySearch('lic', ['licia', 'll', 'lic']); // -> ['lic', 'licia'] console.log(fuzzySearch('beta', [{ name: 'alpha-test-1', age:"123", }, { name: 'beta-test', age:"111", }], { key: "name" //指定搜索key })); ; // -> [ { name: 'beta-test', age: '111' } ] ``` ### pick 过滤需要的 key ``` pick({a: 1, b: 2}, 'a'); // -> {a: 1} pick({a: 1, b: 2, c: 3}, ['b', 'c']) // -> {b: 2, c: 3} pick({a: 1, b: 2, c: 3, d: 4}, function (val, key) { return val % 2; }); // -> {a: 1, c: 3} ``` ### pairs 对象的 key/value 转二维素组 ``` pairs({a: 1, b: 2}); // -> [['a', 1], ['b', 2]] ``` ### values ``` values({one: 1, two: 2}); // -> [1, 2] ``` ## 时间 ### dateFormat ``` dateFormat('isoDate'); // -> 2016-11-19 dateFormat('yyyy-mm-dd HH:MM:ss'); // -> 2016-11-19 19:00:04 dateFormat(new Date(), 'yyyy-mm-dd'); // -> 2016-11-19 ``` ### moment ``` moment('20180501').format('yyyy-mm-dd'); // -> '2018-05-01' ``` ### ms 时间转毫秒 ``` ms('1s'); // -> 1000 ms('1m'); // -> 60000 ms('1.5h'); // -> 5400000 ms('1d'); // -> 86400000 ms('1y'); // -> 31557600000 ms('1000'); // -> 1000 ms(1500); // -> '1.5s' ms(60000); // -> '1m' ``` ### now 毫秒级时间戳 ``` now(); // -> 1468826678701 ``` ## 其他 ### Emitter 点阅发布 ``` var Emitter = require("licia/Emitter"); var event = new Emitter(); event.on('test', function () { console.log('test') }); // event.off("test") //关闭 test 的订阅 event.emit('test'); // Logs out 'test'. event.once("test_one",function () { console.log('test_one') }); event.emit("test_one") event.emit("test_one") //不触发 test_one ``` ### fileType ``` const fs = require('fs'); const file = fs.readFileSync('path/to/file'); console.log(fileType(file)); // -> { ext: 'jpg', mime: 'image/jpeg' } ``` ### fnArgs 验证函数所传的参数 ``` function test(a, b, c) { fnArgs([ 'number|string', //第一个参数为整数或字符串 '?Function', //非必须,传入函数 '...number', ], arguments); // Do something. } test(15); test('test', () => {}); test('test', () => {}, 5); test(); // Throw error test('test', 'test'); // Throw error test('test', () => {}, 5, 'test') // Throw error ``` ### kill 杀掉进程 `kill(9420);` ### getPort 如果首选端口不可用将返回随机端口 ``` ar getPort = require("licia/getPort"); getPort([22], '127.0.0.1').then(port => { console.log(port); }); ``` ### open 打开系统默认方式打开文件或网址 ``` open('https://eustia.liriliri.io/'); ``` ### mkdir ``` mkdir('/tmp/foo/bar/baz', function (err) { if (err) console.log(err); else console.log('Done'); }); ``` ### rmdir ``` rmdir('/tmp/foo/bar/baz', function (err) { if (err) console.log (err); else console.log('Done'); }); ``` ## is 判断 ### isAbsoluteUrl ``` isAbsoluteUrl('http://www.surunzi.com'); // -> true isAbsoluteUrl('//www.surunzi.com'); // -> false isAbsoluteUrl('surunzi.com'); // -> false ``` ### isArr 判断是数组不是对象 ``` isArr([]); // -> true isArr({}); // -> false ``` ### isArrayBuffer ``` isArrBuffer(new ArrayBuffer(8)); // -> true ``` ### isBool ``` isBool(true); // -> true isBool(false); // -> true isBool(1); // -> false ``` ### isBrowser 判断是否跑在浏览器上 ``` console.log(isBrowser); // -> true if running in a browser ``` ### isBuffer ### isDataUrl ``` isDataUrl('http://eustia.liriliri.io'); // -> false isDataUrl('data:text/plain;base64,SGVsbG8sIFdvcmxkIQ%3D%3D'); // -> true ``` ### isDate ``` isDate(new Date()); // -> true ``` ### isEl 是否是 DOM ``` isEl(document.body); // -> true ``` ### isEmail ### isEmpty ``` isEmpty([]); // -> true isEmpty({}); // -> true isEmpty(''); // -> true ``` ### isEqual 对比 对象,字符串等 ``` isEqual([1, 2, 3], [1, 2, 3]); // -> true ``` ### isErr ``` isErr(new Error()); // -> true ``` ### isFn 是否是函数 ### isInt 是否是整数 ### isIp 是否是 ipv4,ipv6 ``` isIp('192.168.191.1'); // -> true isIp('1:2:3:4:5:6:7:8'); // -> true isIp('test'); // -> false isIp.v4('192.168.191.1'); // -> true isIp.v6('1:2:3:4:5:6:7:8'); // -> true ``` ### isJson ``` isJson('{"a": 5}'); // -> true isJson("{'a': 5}"); // -> false ``` ### isMatch key,value 是否在查找的对象中 ``` isMatch({a: 1, b: 2}, {a: 1}); // -> true ``` ### isMiniProgram 检测是否在微信小程序上 ``` console.log(isMiniProgram); // -> true if running in mini program. ``` ### isMobile ``` isMobile(navigator.userAgent); ``` ### isNaN ``` isNaN(0); // -> false isNaN(NaN); // -> true ``` ### isNil 是否是null or undefined ``` isNil(null); // -> true isNil(void 0); // -> true isNil(undefined); // -> true isNil(false); // -> false isNil(0); // -> false isNil([]); // -> false ``` ### isNode 是否在 node 中运行 ``` console.log(isNode); // -> true if running in node ``` ### isNull ### isNumeric ``` isNumeric(1); // -> true isNumeric('1'); // -> true isNumeric(Number.MAX_VALUE); // -> true isNumeric(0xFF); // -> true isNumeric(''); // -> false isNumeric('1.1.1'); // -> false isNumeric(NaN); // -> false ``` ### isObj ``` isObj({}); // -> true isObj([]); // -> true ``` ### isPortFree 检查对口是否占用 ``` isPortFree(3000).then(isFree => { // Do something. }); ``` ### isRelative 文件是否存在 ``` isRelative('README.md'); // -> true ``` ### isUrl ``` isUrl('http://www.example.com?foo=bar&param=test'); // -> true isUrl("www.baidu.com") //false ``` ### isWindows ``` console.log(isWindows); // -> true if running on windows ``` ## to ### toBool ``` toBool(true); // -> true toBool(null); // -> false toBool(1); // -> true toBool(0); // -> false toBool('0'); // -> false toBool('1'); // -> true toBool('false'); // -> false ``` ### toDate ``` toDate('20180501'); toDate('2018-05-01'); toDate(1525107450849); ``` ### toInt ``` toInt(1.1); // -> 1 toInt(undefined); // -> 0 ``` ### toNum ``` toNum('5'); // -> 5 ``` ### type ``` type(5); // -> 'number' type({}); // -> 'object' type(function () {}); // -> 'function' type([]); // -> 'array' type([], false); // -> 'Array' type(async function () {}, false); // -> 'AsyncFunction' ```