utils.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. function arrayMin( array ) {
  2. if ( array.length === 0 ) return Infinity;
  3. let min = array[ 0 ];
  4. for ( let i = 1, l = array.length; i < l; ++ i ) {
  5. if ( array[ i ] < min ) min = array[ i ];
  6. }
  7. return min;
  8. }
  9. function arrayMax( array ) {
  10. if ( array.length === 0 ) return - Infinity;
  11. let max = array[ 0 ];
  12. for ( let i = 1, l = array.length; i < l; ++ i ) {
  13. if ( array[ i ] > max ) max = array[ i ];
  14. }
  15. return max;
  16. }
  17. const TYPED_ARRAYS = {
  18. Int8Array: Int8Array,
  19. Uint8Array: Uint8Array,
  20. Uint8ClampedArray: Uint8ClampedArray,
  21. Int16Array: Int16Array,
  22. Uint16Array: Uint16Array,
  23. Int32Array: Int32Array,
  24. Uint32Array: Uint32Array,
  25. Float32Array: Float32Array,
  26. Float64Array: Float64Array
  27. };
  28. function getTypedArray( type, buffer ) {
  29. return new TYPED_ARRAYS[ type ]( buffer );
  30. }
  31. function createElementNS( name ) {
  32. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  33. }
  34. /**
  35. * cyrb53 hash for string from: https://stackoverflow.com/a/52171480
  36. *
  37. * Public Domain, @bryc - https://stackoverflow.com/users/815680/bryc
  38. *
  39. * It is roughly similar to the well-known MurmurHash/xxHash algorithms. It uses a combination
  40. * of multiplication and Xorshift to generate the hash, but not as thorough. As a result it's
  41. * faster than either would be in JavaScript and significantly simpler to implement. Keep in
  42. * mind this is not a secure algorithm, if privacy/security is a concern, this is not for you.
  43. *
  44. * @param {string} str
  45. * @param {number} seed, default 0
  46. * @returns number
  47. */
  48. function hashString( str, seed = 0 ) {
  49. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  50. for ( let i = 0, ch; i < str.length; i ++ ) {
  51. ch = str.charCodeAt( i );
  52. h1 = Math.imul( h1 ^ ch, 2654435761 );
  53. h2 = Math.imul( h2 ^ ch, 1597334677 );
  54. }
  55. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 ) ^ Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  56. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 ) ^ Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  57. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  58. }
  59. export { arrayMin, arrayMax, getTypedArray, createElementNS, hashString };