util.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. function zero2(word) {
  2. if (word.length === 1) {
  3. return '0' + word;
  4. }
  5. else {
  6. return word;
  7. }
  8. }
  9. export function toArray(msg, enc) {
  10. if (Array.isArray(msg)) {
  11. return msg.slice();
  12. }
  13. if (!msg) {
  14. return [];
  15. }
  16. const res: number[] = [];
  17. if (typeof msg !== 'string') {
  18. for (let i = 0; i < msg.length; i++) {
  19. res[i] = msg[i] | 0;
  20. }
  21. return res;
  22. }
  23. if (enc === 'hex') {
  24. msg = msg.replace(/[^a-z0-9]+/ig, '');
  25. if (msg.length % 2 !== 0) {
  26. msg = '0' + msg;
  27. }
  28. for (let i = 0; i < msg.length; i += 2) {
  29. res.push(parseInt(msg[i] + msg[i + 1], 16));
  30. }
  31. } else {
  32. for (let i = 0; i < msg.length; i++) {
  33. const c = msg.charCodeAt(i);
  34. const hi = c >> 8;
  35. const lo = c & 0xff;
  36. if (hi) {
  37. res.push(hi, lo);
  38. }
  39. else {
  40. res.push(lo);
  41. }
  42. }
  43. }
  44. return res;
  45. }
  46. export function encodeHex(msg: Buffer | Uint8Array) {
  47. let res = '';
  48. for (let i = 0; i < msg.length; i++) {
  49. res += zero2(msg[i].toString(16));
  50. }
  51. return res;
  52. }
  53. export function uuid(): string {
  54. return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
  55. // tslint:disable-next-line: no-bitwise
  56. const random = Math.random() * 16 | 0;
  57. const value = char === "x" ? random : (random % 4 + 8);
  58. return value.toString(16);
  59. });
  60. }
  61. export function isObject(item) {
  62. return (item && typeof item === 'object' && !Array.isArray(item));
  63. }
  64. export function mergeDeep(target: object, source: object) {
  65. const output = Object.assign({}, target);
  66. if (isObject(target) && isObject(source)) {
  67. Object.keys(source).forEach(key => {
  68. if (isObject(source[key])) {
  69. if (!(key in target)) {
  70. Object.assign(output, { [key]: source[key] });
  71. }
  72. else {
  73. output[key] = mergeDeep(target[key], source[key]);
  74. }
  75. } else {
  76. Object.assign(output, { [key]: source[key] });
  77. }
  78. });
  79. }
  80. return output;
  81. }