util.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 err = false;
  31. var copy = Array.prototype.slice.call(arguments);
  32. copy.unshift('PeerJS: ');
  33. for (var i = 0, l = copy.length; i < l; i++){
  34. if (copy[i] instanceof Error) {
  35. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  36. err = true;
  37. }
  38. }
  39. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  40. }
  41. },
  42. setZeroTimeout: (function(global) {
  43. var timeouts = [];
  44. var messageName = 'zero-timeout-message';
  45. // Like setTimeout, but only takes a function argument. There's
  46. // no time argument (always zero) and no arguments (you have to
  47. // use a closure).
  48. function setZeroTimeoutPostMessage(fn) {
  49. timeouts.push(fn);
  50. global.postMessage(messageName, '*');
  51. }
  52. function handleMessage(event) {
  53. if (event.source == global && event.data == messageName) {
  54. if (event.stopPropagation) {
  55. event.stopPropagation();
  56. }
  57. if (timeouts.length) {
  58. timeouts.shift()();
  59. }
  60. }
  61. }
  62. if (global.addEventListener) {
  63. global.addEventListener('message', handleMessage, true);
  64. } else if (global.attachEvent) {
  65. global.attachEvent('onmessage', handleMessage);
  66. }
  67. return setZeroTimeoutPostMessage;
  68. }(this)),
  69. blobToArrayBuffer: function(blob, cb){
  70. var fr = new FileReader();
  71. fr.onload = function(evt) {
  72. cb(evt.target.result);
  73. };
  74. fr.readAsArrayBuffer(blob);
  75. },
  76. blobToBinaryString: function(blob, cb){
  77. var fr = new FileReader();
  78. fr.onload = function(evt) {
  79. cb(evt.target.result);
  80. };
  81. fr.readAsBinaryString(blob);
  82. },
  83. binaryStringToArrayBuffer: function(binary) {
  84. var byteArray = new Uint8Array(binary.length);
  85. for (var i = 0; i < binary.length; i++) {
  86. byteArray[i] = binary.charCodeAt(i) & 0xff;
  87. }
  88. return byteArray.buffer;
  89. },
  90. randomToken: function () {
  91. return Math.random().toString(36).substr(2);
  92. }
  93. };