util.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. var util = {
  2. debug: false,
  3. browserisms: '',
  4. inherits: function(ctor, superCtor) {
  5. ctor.super_ = superCtor;
  6. ctor.prototype = Object.create(superCtor.prototype, {
  7. constructor: {
  8. value: ctor,
  9. enumerable: false,
  10. writable: true,
  11. configurable: true
  12. }
  13. });
  14. },
  15. extend: function(dest, source) {
  16. for(var key in source) {
  17. if(source.hasOwnProperty(key)) {
  18. dest[key] = source[key];
  19. }
  20. }
  21. return dest;
  22. },
  23. pack: BinaryPack.pack,
  24. unpack: BinaryPack.unpack,
  25. randomPort: function() {
  26. return Math.round(Math.random() * 60535) + 5000;
  27. },
  28. log: function () {
  29. if (util.debug) {
  30. var copy = [];
  31. for (var i = 0; i < arguments.length; i++) {
  32. copy[i] = arguments[i];
  33. }
  34. copy.unshift('PeerJS: ');
  35. console.log.apply(console, copy);
  36. }
  37. },
  38. setZeroTimeout: (function(global) {
  39. var timeouts = [];
  40. var messageName = 'zero-timeout-message';
  41. // Like setTimeout, but only takes a function argument. There's
  42. // no time argument (always zero) and no arguments (you have to
  43. // use a closure).
  44. function setZeroTimeoutPostMessage(fn) {
  45. timeouts.push(fn);
  46. global.postMessage(messageName, '*');
  47. }
  48. function handleMessage(event) {
  49. if (event.source == global && event.data == messageName) {
  50. if (event.stopPropagation) {
  51. event.stopPropagation();
  52. }
  53. if (timeouts.length) {
  54. timeouts.shift()();
  55. }
  56. }
  57. }
  58. if (global.addEventListener) {
  59. global.addEventListener('message', handleMessage, true);
  60. } else if (global.attachEvent) {
  61. global.attachEvent('onmessage', handleMessage);
  62. }
  63. return setZeroTimeoutPostMessage;
  64. }(this)),
  65. blobToArrayBuffer: function(blob, cb){
  66. var fr = new FileReader();
  67. fr.onload = function(evt) {
  68. cb(evt.target.result);
  69. };
  70. fr.readAsArrayBuffer(blob);
  71. },
  72. blobToBinaryString: function(blob, cb){
  73. var fr = new FileReader();
  74. fr.onload = function(evt) {
  75. cb(evt.target.result);
  76. };
  77. fr.readAsBinaryString(blob);
  78. },
  79. binaryStringToArrayBuffer: function(binary) {
  80. var byteArray = new Uint8Array(binary.length);
  81. for (var i = 0; i < binary.length; i++) {
  82. byteArray[i] = binary.charCodeAt(i) & 0xff;
  83. }
  84. return byteArray.buffer;
  85. },
  86. randomToken: function () {
  87. return Math.random().toString(36).substr(2);
  88. }
  89. };