租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

338 lines
11 KiB

2 months ago
  1. # utility
  2. [![NPM version][npm-image]][npm-url]
  3. [![build status][travis-image]][travis-url]
  4. [![Test coverage][codecov-image]][codecov-url]
  5. [![npm download][download-image]][download-url]
  6. [![Dependency Status][dependency-image]][dependency-url]
  7. [![devDependency Status][devDependency-image]][devDependency-url]
  8. [npm-image]: https://img.shields.io/npm/v/utility.svg?style=flat-square
  9. [npm-url]: https://npmjs.org/package/utility
  10. [travis-image]: https://img.shields.io/travis/node-modules/utility.svg?style=flat-square
  11. [travis-url]: https://travis-ci.org/node-modules/utility
  12. [codecov-image]: https://codecov.io/github/node-modules/utility/coverage.svg?branch=master
  13. [codecov-url]: https://codecov.io/github/node-modules/utility?branch=master
  14. [download-image]: https://img.shields.io/npm/dm/utility.svg?style=flat-square
  15. [download-url]: https://npmjs.org/package/utility
  16. [dependency-image]: https://david-dm.org/node-modules/utility.svg
  17. [dependency-url]: https://david-dm.org/node-modules/utility
  18. [devDependency-image]: https://david-dm.org/node-modules/utility/dev-status.svg
  19. [devDependency-url]: https://david-dm.org/node-modules/utility#info=devDependencies
  20. A collection of useful utilities.
  21. ## Install
  22. ```bash
  23. $ npm install utility
  24. ```
  25. ## Usage
  26. ```js
  27. const utils = require('utility');
  28. ```
  29. Also you can use it within typescript, like this ↓
  30. ```js
  31. import * as utility from 'utility';
  32. ```
  33. ### md5
  34. ```js
  35. utils.md5('苏千').should.equal('5f733c47c58a077d61257102b2d44481');
  36. utils.md5(Buffer.from('苏千')).should.equal('5f733c47c58a077d61257102b2d44481');
  37. // md5 base64 format
  38. utils.md5('苏千', 'base64'); // 'X3M8R8WKB31hJXECstREgQ=='
  39. // Object md5 hash. Sorted by key, and JSON.stringify. See source code for detail
  40. utils.md5({foo: 'bar', bar: 'foo'}).should.equal(utils.md5({bar: 'foo', foo: 'bar'}));
  41. ```
  42. ### sha1
  43. ```js
  44. utils.sha1('苏千').should.equal('0a4aff6bab634b9c2f99b71f25e976921fcde5a5');
  45. utils.sha1(Buffer.from('苏千')).should.equal('0a4aff6bab634b9c2f99b71f25e976921fcde5a5');
  46. // sha1 base64 format
  47. utils.sha1('苏千', 'base64'); // 'Ckr/a6tjS5wvmbcfJel2kh/N5aU='
  48. // Object sha1 hash. Sorted by key, and JSON.stringify. See source code for detail
  49. utils.sha1({foo: 'bar', bar: 'foo'}).should.equal(utils.sha1({bar: 'foo', foo: 'bar'}));
  50. ```
  51. ### sha256
  52. ```js
  53. utils.sha256(Buffer.from('苏千')).should.equal('75dd03e3fcdbba7d5bec07900bae740cc8e361d77e7df8949de421d3df5d3635');
  54. ```
  55. ### hmac
  56. ```js
  57. // hmac-sha1 with base64 output encoding
  58. utils.hmac('sha1', 'I am a key', 'hello world'); // 'pO6J0LKDxRRkvSECSEdxwKx84L0='
  59. ```
  60. ### decode and encode
  61. ```js
  62. // base64 encode
  63. utils.base64encode('你好¥'); // '5L2g5aW977+l'
  64. utils.base64decode('5L2g5aW977+l') // '你好¥'
  65. // urlsafe base64 encode
  66. utils.base64encode('你好¥', true); // '5L2g5aW977-l'
  67. utils.base64decode('5L2g5aW977-l', true); // '你好¥'
  68. // html escape and unescape
  69. utils.escape('<script/>"& &amp;'); // '&lt;script/&gt;&quot;&amp; &amp;amp;'
  70. utils.unescape('&lt;script/&gt;&quot;&amp; &amp;amp;'); // '<script/>"& &amp;'
  71. // Safe encodeURIComponent and decodeURIComponent
  72. utils.decodeURIComponent(utils.encodeURIComponent('你好, nodejs')).should.equal('你好, nodejs');
  73. ```
  74. ### others
  75. ___[WARNNING] getIP() remove, PLEASE use `https://github.com/node-modules/address` module instead.___
  76. ```js
  77. // get a function parameter's names
  78. utils.getParamNames(function (key1, key2) {}); // ['key1', 'key2']
  79. // get a random string, default length is 16.
  80. utils.randomString(32, '1234567890'); //18774480824014856763726145106142
  81. // check if object has this property
  82. utils.has({hello: 'world'}, 'hello'); //true
  83. // empty function
  84. utils.noop = function () {}
  85. // throw out an assertion error if you were given an invalid "func"
  86. try {
  87. utils.getParamNames(null); // Only function is allowed
  88. } catch (err) {
  89. console.error(err); // Assertion Error
  90. }
  91. ```
  92. ### Date utils
  93. ```js
  94. // accessLogDate
  95. utils.accessLogDate(); // '16/Apr/2013:16:40:09 +0800'
  96. // logDate,
  97. // 'YYYY-MM-DD HH:mm:ss.SSS' format date string
  98. utils.logDate(); // '2013-04-17 14:43:02.674'
  99. utils.YYYYMMDDHHmmssSSS(); // '2013-04-17 14:43:02.674'
  100. utils.YYYYMMDDHHmmssSSS(','); // '2013-04-17 14:43:02,674'
  101. // 'YYYY-MM-DD HH:mm:ss' format date string
  102. utils.YYYYMMDDHHmmss(); // '2013-04-17 14:43:02'
  103. utils.YYYYMMDDHHmmss(new Date(), {dateSep: '.'}); // '2013.04.17 14:43:02'
  104. // 'YYYY-MM-DD' format date string
  105. utils.YYYYMMDD(); // '2013-04-17'
  106. utils.YYYYMMDD(''); // '20130417'
  107. utils.YYYYMMDD(','); // '2013,04,17'
  108. // datestruct
  109. utils.datestruct(); // { YYYYMMDD: 20130416, H: 8 }
  110. // Unix's timestamp
  111. utils.timestamp(); // 1378153226
  112. // Parse timestamp
  113. // seconds
  114. utils.timestamp(1385091596); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST)
  115. // millseconds
  116. utils.timestamp(1385091596000); // Fri Nov 22 2013 11:39:56 GMT+0800 (CST)
  117. ```
  118. ### Number utils
  119. ```js
  120. // Detect a number string can safe convert to Javascript Number.: `-9007199254740991 ~ 9007199254740991`
  121. utils.isSafeNumberString('9007199254740991'); // true
  122. utils.isSafeNumberString('9007199254740993'); // false
  123. // Convert string to number safe:
  124. utils.toSafeNumber('9007199254740991'); // 9007199254740991
  125. utils.toSafeNumber('9007199254740993'); // '9007199254740993'
  126. // Produces a random integer between the inclusive `lower` and exclusive `upper` bounds.
  127. utils.random(100); // [0, 100)
  128. utils.random(2, 1000); // [2, 1000)
  129. utils.random(); // 0
  130. ```
  131. ### Timers
  132. ```js
  133. utils.setImmediate(function () {
  134. console.log('hi');
  135. });
  136. ```
  137. ### map
  138. Create a `real` map in javascript.
  139. use `Object.create(null)`
  140. ```js
  141. const map = utils.map({a: 1});
  142. // should.not.exist(map.constructor);
  143. // should.not.exist(map.__proto__);
  144. // should.not.exist(map.toString);
  145. // should not exist any property
  146. console.log(map); // {a: 1}
  147. ```
  148. ### String utils
  149. ```js
  150. // split string by sep
  151. utils.split('foo,bar,,,', ','); // ['foo', 'bar']
  152. // replace string work with special chars which `String.prototype.replace` can't handle
  153. utils.replace('<body> hi', '<body>', '$& body'); // '$& body hi'
  154. // replace http header invalid characters
  155. utils.replaceInvalidHttpHeaderChar('abc你好11'); // {invalid: true, val: 'abc 11'}
  156. ```
  157. ### Try
  158. ```js
  159. const res = utils.try(function () {
  160. return JSON.parse(str);
  161. });
  162. // {error: undefined, value: {foo: 'bar'}}
  163. // {error: Error, value: undefined}
  164. ```
  165. ```Note``` that when you use ```typescript```, you must use the following methods to call ' Try '
  166. ```js
  167. import * as utility from 'utility';
  168. utility.UNSTABLE_METHOD.try(...);
  169. ...
  170. ```
  171. ### argumentsToArray
  172. ```js
  173. function() {
  174. const arr = utility.argumentsToArray(arguments);
  175. console.log(arr.join(', '));
  176. }
  177. ```
  178. ### JSON
  179. ```js
  180. const obj = utils.strictJSONparse('"hello"');
  181. // will throw when JSON string is not object
  182. const pkg = utils.readJSONSync('package.json');
  183. utils.writeJSONSync('package.json', pkg, {
  184. replacer: null,
  185. space: '\t',
  186. });
  187. ```
  188. Or you can use async API
  189. ```js
  190. async () => {
  191. const pkg = await utils.readJSON('package.json');
  192. await utils.writeJSON('package.json', pkg);
  193. }
  194. ```
  195. > **Hint:** In `utils.writeJSON*()`, if `pkg` is an object, the **optional** third parameter `options` may contain two
  196. > keys.
  197. >
  198. > + `replacer`: Equals to `JSON.stringify()`'s second parameter;
  199. > + `space`: Equals to `JSON.stringify()`'s third parameter. Defaults to `2`.
  200. >
  201. > Refs:
  202. >
  203. > + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter
  204. > + https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_space_argument
  205. ### Object.assign
  206. ```js
  207. // assign object
  208. utility.assign({}, { a: 1 });
  209. // assign multiple object
  210. utility.assign({}, [ { a: 1 }, { b: 1 } ]);
  211. ```
  212. ## benchmark
  213. * [jsperf: access log date format](http://jsperf.com/access-log-date-format)
  214. * [benchmark/date_format.js](https://github.com/fengmk2/utility/blob/master/benchmark/date_format.js)
  215. ```bash
  216. $ node benchmark/date_format.js
  217. moment().format("DD/MMM/YYYY:HH:mm:ss ZZ"): "16/Apr/2013:21:12:32 +0800"
  218. utils.accessLogDate(): "16/Apr/2013:21:12:32 +0800"
  219. fasterAccessDate(): "16/Apr/2013:21:12:32 +0800"
  220. fasterAccessDate2(): "16/Apr/2013:21:12:32 +0800"
  221. new Date().toString(): "Tue Apr 16 2013 21:12:32 GMT+0800 (CST)"
  222. Date(): "Tue Apr 16 2013 21:12:32 GMT+0800 (CST)"
  223. Date.now(): 1366117952162
  224. ------------------------
  225. moment().format('DD/MMM/YYYY:HH:mm:ss ZZ') x 68,300 ops/sec ±5.05% (91 runs sampled)
  226. utils.accessLogDate() x 1,341,341 ops/sec ±2.72% (90 runs sampled)
  227. fasterAccessDate() x 357,833 ops/sec ±1.32% (98 runs sampled)
  228. fasterAccessDate2() x 301,607 ops/sec ±5.03% (83 runs sampled)
  229. new Date().toString() x 738,499 ops/sec ±3.54% (86 runs sampled)
  230. Date() x 794,724 ops/sec ±2.77% (95 runs sampled)
  231. Date.now() x 8,327,685 ops/sec ±1.85% (94 runs sampled)
  232. Fastest is Date.now()
  233. ```
  234. [benchmark/date_YYYYMMDD.js](https://github.com/fengmk2/utility/blob/master/benchmark/date_YYYYMMDD.js)
  235. ```bash
  236. $ node benchmark/date_YYYYMMDD.js
  237. parseInt(moment().format("YYYYMMDD"), 10): 20130416
  238. utils.datestruct().YYYYMMDD: 20130416
  239. new Date().toString(): "Tue Apr 16 2013 21:12:02 GMT+0800 (CST)"
  240. ------------------------
  241. parseInt(moment().format('YYYYMMDD'), 10) x 129,604 ops/sec ±0.46% (101 runs sampled)
  242. utils.datestruct().YYYYMMDD x 2,317,461 ops/sec ±1.38% (95 runs sampled)
  243. new Date().toString() x 816,731 ops/sec ±3.46% (93 runs sampled)
  244. Fastest is utils.datestruct().YYYYMMDD
  245. ```
  246. <!-- GITCONTRIBUTOR_START -->
  247. ## Contributors
  248. |[<img src="https://avatars0.githubusercontent.com/u/156269?v=4" width="100px;"/><br/><sub><b>fengmk2</b></sub>](https://github.com/fengmk2)<br/>|[<img src="https://avatars3.githubusercontent.com/u/985607?v=4" width="100px;"/><br/><sub><b>dead-horse</b></sub>](https://github.com/dead-horse)<br/>|[<img src="https://avatars1.githubusercontent.com/u/1147375?v=4" width="100px;"/><br/><sub><b>alsotang</b></sub>](https://github.com/alsotang)<br/>|[<img src="https://avatars1.githubusercontent.com/u/360661?v=4" width="100px;"/><br/><sub><b>popomore</b></sub>](https://github.com/popomore)<br/>|[<img src="https://avatars2.githubusercontent.com/u/1207064?v=4" width="100px;"/><br/><sub><b>gxcsoccer</b></sub>](https://github.com/gxcsoccer)<br/>|[<img src="https://avatars3.githubusercontent.com/u/2842176?v=4" width="100px;"/><br/><sub><b>XadillaX</b></sub>](https://github.com/XadillaX)<br/>|
  249. | :---: | :---: | :---: | :---: | :---: | :---: |
  250. [<img src="https://avatars1.githubusercontent.com/u/24466804?v=4" width="100px;"/><br/><sub><b>mosikoo</b></sub>](https://github.com/mosikoo)<br/>|[<img src="https://avatars2.githubusercontent.com/u/2569835?v=4" width="100px;"/><br/><sub><b>haoxins</b></sub>](https://github.com/haoxins)<br/>|[<img src="https://avatars1.githubusercontent.com/u/546535?v=4" width="100px;"/><br/><sub><b>leoner</b></sub>](https://github.com/leoner)<br/>|[<img src="https://avatars3.githubusercontent.com/u/33921398?v=4" width="100px;"/><br/><sub><b>ddzy</b></sub>](https://github.com/ddzy)<br/>
  251. This project follows the git-contributor [spec](https://github.com/xudafeng/git-contributor), auto updated at `Sat Mar 23 2019 12:09:41 GMT+0800`.
  252. <!-- GITCONTRIBUTOR_END -->
  253. ## License
  254. [MIT](LICENSE.txt)