{"id":13671703,"url":"https://github.com/leeenx/es6-utils","last_synced_at":"2025-04-27T18:31:35.279Z","repository":{"id":90408397,"uuid":"102843805","full_name":"leeenx/es6-utils","owner":"leeenx","description":"存放一些 es6 小工具","archived":false,"fork":false,"pushed_at":"2022-03-07T05:59:41.000Z","size":99,"stargazers_count":100,"open_issues_count":0,"forks_count":28,"subscribers_count":9,"default_branch":"master","last_synced_at":"2024-11-11T09:44:01.422Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/leeenx.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-09-08T09:24:12.000Z","updated_at":"2023-03-02T20:19:15.000Z","dependencies_parsed_at":"2023-03-13T17:58:41.339Z","dependency_job_id":null,"html_url":"https://github.com/leeenx/es6-utils","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leeenx%2Fes6-utils","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leeenx%2Fes6-utils/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leeenx%2Fes6-utils/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/leeenx%2Fes6-utils/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/leeenx","download_url":"https://codeload.github.com/leeenx/es6-utils/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251187251,"owners_count":21549609,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-02T09:01:16.719Z","updated_at":"2025-04-27T18:31:34.944Z","avatar_url":"https://github.com/leeenx.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# es6-utils\n本项目用于存放一些 es6 小工具\n\n## randomList\n随机打散数组，并返回指数量与指定条件的数组。\n\n语法：\n\u003e randomList(list, count, filter)  \n\n**parameters**\n\n| name | type | detail |\n| :-- | :-- | :-- |\n| list | Array | 目标数组 |\n| count | Number | 返回的数组的个数 | \n| filter | Function | 过滤条件函数 |\n\n**return**: [keys, vals]\n\n具体参见：\n```javascript\n// 引用模块\nimport randomList from `./modules/randomList`; \n\n// 调用如下\nlet [keys, vals] = randomList([1, 2, 3, 4, 5], 2, (num) =\u003e num\u003e5); \n```\n\n## Chain\n\n语法：\n\u003e new Chain(Array)  \n\n将传入的数组转化为一个链表。\n\n**return**: {shift, unshift, pop, push, insertAfter, insertAfter, prev, next, curr, first, last, remove, add, clone, reverse, slice, splice, concat, reverse, length, *setPointer, *setHead, *setTail, *HEAD, *TAIL, *POINTER, [Symbol.iterator]}\n\n| name | type | syntax | detail |\n| :-- | :-- | :-- | :-- |\n| shift | Function | chain.shift() | 删除链表第一个节点，并返回这个节点。|\n| unshift | Function | chain.unshift(node1[, node2, node3, ...]) | 向链表头部插入一个或多个节点节点。| \n| pop | Function | chain.pop() | 删除链表最后一个，并返回这个节点。 |\n| push | Function | chain.push(node1[, node2, node3, ...]) | 向链表尾部插入一个或多个节点。 参考数组的 push | \n| at | Function | chain.at(index) | 返回指定索引的节点，并将 POINTER 指向当前位置 |\n| prev | Function | chain.prev() | 返回当前节点，并把 POINTER 指向上一个节点 |\n| next | Function | chain.next() | 返回当前节点，并把 POINTER 指向上一个节点 |\n| curr | Function | chain.curr() | 返回当前节点 |\n| first | Function | chain.first() | 返回头节点 |\n| last | Function | chain.last() | 返回尾节点 |\n| indexOf | Function | chain.indexOf(value, fromIndex) | 返回 value 的索引位置，如果没有返回 -1 | \n| sort | Function | chain.sort(compare) | 链表排序 | \n| remove | Function | chain.remove(start[, end]) | 删除指定索引范围的节点，返回一个Chain实例。|\n| insertAfter | Function | chain.insertAfter(index, node1[, node2, node3, ...]) | 向指定索引后插入节点。 |\n| insertBefore | Function | chain.insertBefore(index, node1[, node2, node3, ...]) | 向指定索引前插入节点。 |\n| insertChainAfter | Function | chainA.insertChainAfter(index, chainB) | 向指定索引后插入链表。 |\n| insertChainBefore | Function | chainA.insertChainBefore(index, chainB) | 向指定索引前插入链表。 |\n| slice | Function | chain.slice(start[, end]) | 克隆索引范围的节点，返回一个Chain实例。 |\n| splice | Function | chain.splice(start[, deleteCount, item1, item2, ...]) | 删除索引范围的节点，并在 start 处批量插入指定节点，返回一个 Chain 实例。 |\n| reverse | Function | chain.reverse() | 链表快速反转 | \n| concat | Function | chainA.concat(chainB) | 合并两个链表。 |\n| clone | Function | chain.clone() |  返回一个克隆链表 |\n| length | Number | chain.length | 链表长度 |\n| `*`setPointer | Function | chain.setPointer(node = chain.HEAD) | 设置 POINTER 指针 |\n| `*`setHead | Function | chain.setHead(node) | 设置头指针 |\n| `*`setTail | Function | chain.setTail(node) | 设置尾指针 |\n| `*`HEAD | Object | - | 头指针 |\n| `*`TAIL | Object | - | 尾指针 |\n| `*`POINTER | Object | - | 当前位置指针 | \n| `*`NEXT | String | - | 前驱别名。勿调用！ |\n| `*`PREV | String | - | 后驱别名。勿调用！ |\n| [Symbol.iterator] | Symbol | - | 迭代接口 |\n\n**注意加 `*` 的属性表示内部调用**\n\nChain的实例同时是一个迭代器。如下：\n\n```javascript\nimport Chain from './modules/Chain'; \nlet chain = new Chain([1, 2, 3, 4, 5, 6, 7]); \nfor(let it of chain) {\n  console.log(it.data)\n}\n```\n上面代码输出的结果是：1, 2, 3, 4, 5, 6, 7\n\n利用 next/prev 来做迭代，如下：\n\n```javascript\nlet chain = new Chain([1, 2, 3, 4, 5, 6, 7, 8]), item, i = 0; \nchain.setPointer(3); \nwhile(item = chain.prev()) {\n\tconsole.log(item.data); \n}\n```\n上面的结果是：4, 3, 2, 1\n\n可以跟数组一样操作合并：\n```javascript\nlet chain = new Chain([1, 2, 3, 4, 5]); \nlet chain2 = new Chain([\"a\", \"b\", \"c\", \"d\", \"e\"]); \nchain.concat(chain2); \nfor(let data of chain) {\n\tconsole.log(data); \n}\n```\n输出结果：1, 2, 3, 4, 5, a, b, c, d, e\n\n\n## timer\n统一管理 setTimeout/setInterval 的小库，可以与渲染引擎（如 createjs/PIXI 等）结合使用，也可以单独使用。\n\n默认情况（非游戏开发）：\n```javascript\nimport timer from './modules/timer'; \nlet intervalID = timer.setInterval(() =\u003e console.log(\"++1s++\"), 1000); \ntimer.setTimeout(() =\u003e timer.clearInterval(intervalID), 5000); \n```\n结合 createjs：\n```javascript\nimport timer from './modules/timer'; \n// 统一 ticker\ncreatejs.Ticker.addEventListener(\"tick\", function(e) {\n  e.paused || timer.update(e.delta); \n}); \n// 计时\nlet intervalID = timer.setInterval(() =\u003e console.log(\"++1s++\"), 1000); \n// 5s 后暂停\ntimer.setTimeout(() =\u003e timer.pause(intervaID), 5000);\n// 10s 后继续\ntimer.setTimeout(() =\u003e timer.resume(intervaID), 10000);\n```\n\ntimer 的 APIs 如下：\n\n| name | type | syntax | detail |\n| :-- | :-- | :-- | :-- |\n| setTimeout | Function | let setTimeoutID = timer.setTimeout(fun, delay[, id]) | 替代原生setTimeout，第三个参数表示指定一个有意义的setTimeoutID |\n| clearTimeout | Function | timer.clearTimeout(setTimeoutID) | 清除timer.setTimeout |\n| setInterval | Function | let setIntervalID = timer.setInterval(fun, delay[, id]) | 替代原生setInterval，第三个参数表示指定一个有意义的setIntervalID |\n| clearInterval | Function | timer.clearInterval(setIntervalID) | 清除timer.clearInterval |\n| delete | Function | timer.delete(setTimeoutID/setIntervalID) | 相当于clearTimeout \u0026 clearInterval |\n| pause | Function | timer.pause(setTimeoutID/setIntervalID) | 暂停指定ID的计时，如果没指定ID表示暂停所有计时 |\n| resume | Function | timer.resume(setTimeoutID/setIntervalID) | 恢复指定ID的计时，如果没指定ID表示恢复所有计时 |\n| play | Function | timer.play(setTimeoutID/setIntervalID) | 同 resume |\n| pauseAll | Function | timer.pauseAll() | 暂停所有计时 |\n| playAll | Function | timer.playAll() | 恢复所有计时 | \n| clean | Function | timer.clean() | 清空所有计时 |\n| set | Function | timer.set(id, {fn, delay}) | 重置timer的回调函数与delay |\n| reset | Function | timer.reset(id) | 调用reset后，指定ID的计时会被置零 |\n| resetAll | Function | timer.resetAll() | 调用resetAll后，所有计时会被置零 |\n| useRAF | Boolean | timer.useRAF = true / false | true 表示启用自身RAF，false 反之。与第三方ticker结合时，timer 会自动切换 |\n\n## Event\n事件管理类。语法如下：\n\n\u003e let event = new Event(); \n\nevent实例的API如下：\n\n| name | type | syntac | deltail |\n| :-- | :-- | :-- | :-- |\n| on | Function | event.on(eventName, fn) | 监听一个自定义事件 |\n| off | Function | event.off(eventName, fn) | 移除监听事件，event.off(eventName) 表示删除这个事件的所有监听 |\n| once | Function | event.once(eventName, fn) | 监听一次自定义事件 |\n| clean | Function | event.clean() | 清空所有事件 |\n| dispatch | Function | event.dispatch(eventName, args) | 触发一个自定义事件 |\n\n用法如下：\n\n```javascript\nlet event = new Events(); \nevent.on(\"haha\", function() {\n\tconsole.log(\"haha\"); \n}); \nsetTimeout(() =\u003e event.dispatch(\"haha\")); \n```\n\n## p2angle\n\n计算两点间的角度。用法如下：\n\n```javascript\nexport p2angle from './modules/p2angle'; \np2angle.set(0, 0); \nlet radian = p2angel.get(100, 100); \nconsole.log(\"点(100, 100) 到 原点(0, 0) 的弧度是：\" + radian); \nlet degree = p2angel.getDegree(100, 100); \nconsole.log(\"点(100, 100) 到 原点(0, 0) 的角度是：\" + degree); \n```\np2angle的API如下：\n\n| name | type | detail | \n| :-- | :-- | :-- | \n| set | Function | 设置一个原点 | \n| get | Function | 获取当前点到原点的弧度值 |  \n| getDegree | Function | 获取当前点到原点的角度值 |\n\n注意，这里的角度的取值请参考下图：\n\n![角度](http://7xv39r.com1.z0.glb.clouddn.com/20170924_coord.gif)\n\n## Line\n\n创建一条直线。用法如下：\n```javascript\n// 穿过点\u003cx1, y1\u003e 和 \u003cx2, y2\u003e 的直线\nnew Line({x1, y1}, {x2, y2})\n// 穿过点\u003cx, y\u003e并且斜率为 slope 的直线\nnew Line({x, y}, slope)\n```\n\nAPI 如下：\n\n| name | type | syntax | detail |\n| :-- | :-- | :-- | :-- |\n| distanceFromCoord | Function | distanceFromCoord(x, y) | 返回点\u003cx, y\u003e 到直线的距离 |\n| cross | Function | cross(line) | 两直线的相交点 |\n| getX | function | getX(y) | 返回与 y 坐标对应的 x 坐标值 |\n| getY | function | getY(x) | 返回与 x 坐标对应的 y 坐标值 |\n\n## waveAverage\n\n「波动算法」，用于随机分割数值。通过「波动算法」可以指定分割后的随机数偏离「平均值」的距离，详细可以参考：[波动均分算法](https://aotu.io/notes/2018/01/11/waveaverage/)。\n\n这里提供了两个「波动均分算法」：\n\n- exhaustWave\n- quickWave\n\n### exhaustWave\n\n语法如下： \n\n\u003e exhaustWave(n, crest, trough)；\n\u003e 返回值：分割的结果数组\n\n\nn ----- 表示要分割的份数；\ncrest ------- 波峰值（即距离平均值的正向尺寸）；\ntrough ------- 波谷值（即距离平均值的负向尺寸），默认取 crest 的值；\n\n用法如下：\n```javascript\n// 将 100 分割成 5分，波动为 10\nvar average = 100 / 5; \n// 分配结果\nvar res = exhaustWave(5, 10).map(rnd =\u003e rnd + average)\n```\n\n**exhaustWave 一般不推荐使用，因为效率低下，并且只适用到整数分割**\n\n### quickWave\n\n\u003e quickWave(n, crest, trough, isInteger)；\n\u003e 返回值：分割的结果数组\n\nn ----- 表示要分割的份数；\ncrest ------- 波峰值（即距离平均值的正向尺寸）；\ntrough ------- 波谷值（即距离平均值的负向尺寸），默认取 crest 的值；\nisInteger ------ 是否分割为整数，默认取 true\n\n用法如下：\n```javascript\n// 将 100 分割成 5分，波动为 10\nvar average = 100 / 5; \n// 分配结果\nvar res = quickWave(5, 10, 10, false).map(rnd =\u003e rnd + average)\n```\n**快速分配是推荐的算法，效率高可以分割实数**\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleeenx%2Fes6-utils","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fleeenx%2Fes6-utils","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleeenx%2Fes6-utils/lists"}