helpers.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /**
  2. * This file is part of Threema Web.
  3. *
  4. * Threema Web is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU Affero General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * Convert an Uint8Array to a hex string.
  19. *
  20. * Example:
  21. *
  22. * >>> u8aToHex(new Uint8Array([1, 255]))
  23. * "01ff"
  24. */
  25. export function u8aToHex(array: Uint8Array): string {
  26. const results: string[] = [];
  27. array.forEach((arrayByte) => {
  28. results.push(arrayByte.toString(16).replace(/^([\da-f])$/, '0$1'));
  29. });
  30. return results.join('');
  31. }
  32. /**
  33. * Convert a hexadecimal string to a Uint8Array.
  34. *
  35. * Example:
  36. *
  37. * >>> hexToU8a("01ff")
  38. * [1, 255]
  39. */
  40. export function hexToU8a(hexstring: string): Uint8Array {
  41. let array;
  42. let i;
  43. let j = 0;
  44. let k;
  45. let ref;
  46. // If number of characters is odd, add padding
  47. if (hexstring.length % 2 === 1) {
  48. hexstring = '0' + hexstring;
  49. }
  50. array = new Uint8Array(hexstring.length / 2);
  51. for (i = k = 0, ref = hexstring.length; k <= ref; i = k += 2) {
  52. array[j++] = parseInt(hexstring.substr(i, 2), 16);
  53. }
  54. return array;
  55. }
  56. /**
  57. * Generate a random string.
  58. *
  59. * Based on http://stackoverflow.com/a/1349426/284318.
  60. */
  61. export function randomString(
  62. length = 32,
  63. chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
  64. ): string {
  65. let str = '';
  66. for (let i = 0; i < length; i++) {
  67. str += chars.charAt(Math.floor(Math.random() * chars.length));
  68. }
  69. return str;
  70. }
  71. /* tslint:disable */
  72. /**
  73. * Convert a JS string to a UTF-8 "byte" array.
  74. *
  75. * Copyright 2008 The Closure Library Authors. All Rights Reserved.
  76. *
  77. * Licensed under the Apache License, Version 2.0 (the "License");
  78. * you may not use this file except in compliance with the License.
  79. * You may obtain a copy of the License at
  80. *
  81. * http://www.apache.org/licenses/LICENSE-2.0
  82. *
  83. * Unless required by applicable law or agreed to in writing, software
  84. * distributed under the License is distributed on an "AS-IS" BASIS,
  85. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  86. * See the License for the specific language governing permissions and
  87. * limitations under the License.
  88. *
  89. * https://github.com/google/closure-library/commit/e877b1eac410c0d842bcda118689759512e0e26f
  90. *
  91. * @param {string} str 16-bit unicode string.
  92. * @return {!Array<number>} UTF-8 byte array.
  93. */
  94. export function stringToUtf8a(str: string): Uint8Array {
  95. var out = [], p = 0;
  96. for (var i = 0; i < str.length; i++) {
  97. var c = str.charCodeAt(i);
  98. if (c < 128) {
  99. out[p++] = c;
  100. } else if (c < 2048) {
  101. out[p++] = (c >> 6) | 192;
  102. out[p++] = (c & 63) | 128;
  103. } else if (
  104. ((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&
  105. ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {
  106. // Surrogate Pair
  107. c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
  108. out[p++] = (c >> 18) | 240;
  109. out[p++] = ((c >> 12) & 63) | 128;
  110. out[p++] = ((c >> 6) & 63) | 128;
  111. out[p++] = (c & 63) | 128;
  112. } else {
  113. out[p++] = (c >> 12) | 224;
  114. out[p++] = ((c >> 6) & 63) | 128;
  115. out[p++] = (c & 63) | 128;
  116. }
  117. }
  118. return Uint8Array.from(out);
  119. }
  120. /**
  121. * Convert a UTF-8 byte array to JavaScript's 16-bit Unicode.
  122. *
  123. * Copyright 2008 The Closure Library Authors. All Rights Reserved.
  124. *
  125. * Licensed under the Apache License, Version 2.0 (the "License");
  126. * you may not use this file except in compliance with the License.
  127. * You may obtain a copy of the License at
  128. *
  129. * http://www.apache.org/licenses/LICENSE-2.0
  130. *
  131. * Unless required by applicable law or agreed to in writing, software
  132. * distributed under the License is distributed on an "AS-IS" BASIS,
  133. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  134. * See the License for the specific language governing permissions and
  135. * limitations under the License.
  136. *
  137. * https://github.com/google/closure-library/commit/e877b1eac410c0d842bcda118689759512e0e26f
  138. *
  139. * @param {Uint8Array|Array<number>} bytes UTF-8 byte array.
  140. * @return {string} 16-bit Unicode string.
  141. */
  142. export function utf8aToString(bytes: Uint8Array): string {
  143. var out = [], pos = 0, c = 0;
  144. while (pos < bytes.length) {
  145. var c1 = bytes[pos++];
  146. if (c1 < 128) {
  147. out[c++] = String.fromCharCode(c1);
  148. } else if (c1 > 191 && c1 < 224) {
  149. var c2 = bytes[pos++];
  150. out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63);
  151. } else if (c1 > 239 && c1 < 365) {
  152. // Surrogate Pair
  153. var c2 = bytes[pos++];
  154. var c3 = bytes[pos++];
  155. var c4 = bytes[pos++];
  156. var u = ((c1 & 7) << 18 | (c2 & 63) << 12 | (c3 & 63) << 6 | c4 & 63) - 0x10000;
  157. out[c++] = String.fromCharCode(0xD800 + (u >> 10));
  158. out[c++] = String.fromCharCode(0xDC00 + (u & 1023));
  159. } else {
  160. var c2 = bytes[pos++];
  161. var c3 = bytes[pos++];
  162. out[c++] = String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
  163. }
  164. }
  165. return out.join('');
  166. }
  167. /* tslint:enable */
  168. /**
  169. * Filter an array or object.
  170. */
  171. export function filter(obj: Object | any[], callback: (arg: any) => boolean) {
  172. if (obj instanceof Array) {
  173. // Filter arrays using Array.filter
  174. return (obj as any[]).filter(callback);
  175. } else {
  176. // Filter objects by iterating over them
  177. // and selectively copying values
  178. const out = {};
  179. for (let key in Object.keys(obj)) { // tslint:disable-line:forin
  180. const value = obj[key];
  181. if (callback(value)) {
  182. out[key] = value;
  183. }
  184. }
  185. return out;
  186. }
  187. }
  188. /**
  189. * Check whether a variable is a string.
  190. */
  191. export function isString(val: any): boolean {
  192. return typeof val === 'string' || val instanceof String;
  193. }
  194. /**
  195. * Throttle function.
  196. *
  197. * Taken from https://remysharp.com/2010/07/21/throttling-function-calls
  198. */
  199. export function throttle(fn, threshold: number = 250, scope) {
  200. let last;
  201. let deferTimer;
  202. return function() {
  203. let context = scope || this;
  204. let now = +(new Date());
  205. let args = arguments;
  206. if (last && now < last + threshold) {
  207. // hold on to it
  208. clearTimeout(deferTimer);
  209. deferTimer = setTimeout(function() {
  210. last = now;
  211. fn.apply(context, args);
  212. }, threshold);
  213. } else {
  214. last = now;
  215. fn.apply(context, args);
  216. }
  217. };
  218. }
  219. /**
  220. * Detect whether browser supports passive event listeners.
  221. *
  222. * Taken from https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  223. */
  224. export function supportsPassive() {
  225. // Test via a getter in the options object to see if the passive property is accessed
  226. let supportsPassive = false;
  227. try {
  228. const opts = Object.defineProperty({}, 'passive', {
  229. get: () => supportsPassive = true,
  230. });
  231. window.addEventListener('test', null, opts);
  232. } catch (e) { /* do nothing */ }
  233. }
  234. /**
  235. * Excape a RegEx, so that none of the string characters are considered special characters.
  236. *
  237. * Taken from https://stackoverflow.com/a/17606289/284318
  238. */
  239. export function escapeRegExp(str: string) {
  240. return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  241. }