PageRenderTime 13ms CodeModel.GetById 2ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/Play/util.js

http://github.com/mbebenita/Broadway
JavaScript | 266 lines | 211 code | 33 blank | 22 comment | 45 complexity | c8b560a0810d8bdb1a2c45e96cf555bc MD5 | raw file
  1'use strict';
  2
  3var ERRORS = 0, WARNINGS = 1, TODOS = 5;
  4var verbosity = WARNINGS;
  5
  6function dump(object) {
  7    var output = '{ ';
  8    for ( var property in object) {
  9        output += property + ': ' + object[property] + '; ';
 10    }
 11    output += '}';
 12    log(output);
 13}
 14
 15function getProperties(object, verbose) {
 16    if (verbose) {
 17        var output = '{\n';
 18        for ( var property in object) {
 19            if (typeof (object[property]) != "function") {
 20                if (typeof (object[property]) == "number" && (property.toString().indexOf("word") >= 0)) {
 21                    output += "   " + property + ': ' + getNumberInfo(object[property]) + '\n';
 22                } else {
 23                    output += "   " + property + ': ' + object[property] + '\n';
 24                }
 25            }
 26        }
 27        return output + '}';
 28    } else {
 29        var output = '{ ';
 30        for ( var property in object) {
 31            if (typeof (object[property]) != "function") {
 32                output += property + ': ' + object[property] + ' ';
 33            }
 34        }
 35        return output + '}';
 36    }
 37}
 38
 39function getPrettyEnumValue(object, value) {
 40    return getPropertyByValue(object, value) + " (" + value + ")";
 41}
 42
 43function getPropertyByValue(object, value) {
 44    for ( var property in object) {
 45        if (object[property] == value) {
 46            return property;
 47        }
 48    }
 49    return null;
 50}
 51
 52function log(message) {
 53    console.log(message);
 54}
 55
 56function warn(message) {
 57    if (verbosity >= WARNINGS) {
 58        log('Warning: ' + message);
 59    }
 60}
 61
 62function backtrace() {
 63    var stackStr;
 64    try {
 65        throw new Error();
 66    } catch (e) {
 67        stackStr = e.stack;
 68    }
 69    return stackStr.split('\n').slice(1).join('\n');
 70}
 71
 72function notImplemented() {
 73    error("not implemented");
 74}
 75
 76function unexpected() {
 77    error("unexpected");
 78}
 79
 80function error(message) {
 81  console.error(message);
 82  console.trace();
 83}
 84
 85function assert(condition, message) {
 86  if (!condition) {
 87    error(message);
 88  }
 89}
 90
 91function assertFalse(condition, message) {
 92  if (condition) {
 93      error(message);
 94  }
 95}
 96
 97function assertRange(value, min, max) {
 98    if (value < min || value > max) {
 99        error("Value " + value + " is out of range [" + min + "," + max + "]");
100    }
101}
102
103function bytesToString(bytes) {
104    var str = '';
105    var length = bytes.length;
106    for ( var n = 0; n < length; ++n) {
107        str += String.fromCharCode(bytes[n]);
108    }
109    return str;
110}
111
112function stringToBytes(str) {
113    var length = str.length;
114    var bytes = new Uint8Array(length);
115    for ( var n = 0; n < length; ++n) {
116        bytes[n] = str.charCodeAt(n) & 0xFF;
117    }
118    return bytes;
119}
120
121//
122// getPdf()
123// Convenience function to perform binary Ajax GET
124// Usage: getPdf('http://...', callback)
125// getPdf({
126// url:String ,
127// [,progress:Function, error:Function]
128// },
129// callback)
130//
131function getFile(arg, callback) {
132    var params = arg;
133    if (typeof arg === 'string')
134        params = {
135            url : arg
136        };
137
138    var xhr = new XMLHttpRequest();
139    xhr.open('GET', params.url);
140    xhr.mozResponseType = xhr.responseType = 'arraybuffer';
141    xhr.expected = (document.URL.indexOf('file:') === 0) ? 0 : 200;
142
143    if ('progress' in params) {
144        xhr.onprogrss = params.progress || undefined;
145    }
146
147    if ('error' in params) {
148        xhr.onerror = params.error || undefined;
149    }
150
151    xhr.onreadystatechange = function getPdfOnreadystatechange() {
152        if (xhr.readyState === 4 && xhr.status === xhr.expected) {
153            var data = (xhr.mozResponseArrayBuffer || xhr.mozResponse
154                    || xhr.responseArrayBuffer || xhr.response);
155            callback(data);
156        }
157    };
158    xhr.send(null);
159}
160
161function getBinaryDigits(x, digits, withLeadingZeros) {
162    var t = "";
163    var z = withLeadingZeros ? 0 : countLeadingZeros32(x);
164    for (var i = digits - z - 1; i >= 0; i--) {
165        t += x & (1 << i) ? "1" : "0";
166    }
167    return t;
168}
169
170
171function padLeft(str, char, num) {
172    var pad = "";
173    for ( var i = 0; i < num - str.length; i++) {
174        pad += char;
175    }
176    return pad + str;
177}
178
179function getNumberInfo(x) {
180    return "0x" + getHexBytes(x, 8) + 
181           ", 0b" + getBinaryDigits(x, 16, true) + " (" + countLeadingZeros16(x) + ")" +
182           ", 0b" + getBinaryDigits(x, 32, true) + " (" + countLeadingZeros32(x) + ") " + 
183           x.toString(); 
184}
185
186function getHexBytes(number, length) {
187    if (number < 0) {
188        var u = 0xFFFFFFFF + number + 1;
189        var hex = u.toString(16).toUpperCase();
190        return padLeft(hex, "0", length);
191    }
192    return padLeft(number.toString(16).toUpperCase(), "0", length);
193}
194
195function printArrayBuffer(buffer) {
196    printArray(new Uint8Array(buffer));
197}
198
199function printArray(uint8View) {
200    var group = 64;
201    var subGroup = 4;
202    print("Size: " + uint8View.length + " (" + (uint8View.length * 8) + ")" + ", Buffer: ");
203    for ( var i = 0; i < uint8View.length; i++) {
204        if (i % group == 0) {
205            print("\n");
206            print(getHexBytes(i, 4) + ": ");
207        } else if (i % subGroup == 0) {
208            print(" ");
209        }
210        print(getHexBytes(uint8View[i], 2));
211    }
212    print("\n");
213}
214
215function traceln(s) {
216    println(s);
217}
218
219function isPowerOfTwo(x) {
220  return (x & (x - 1)) == 0;
221}
222
223/**
224 * Rounds up to the next highest power of two.
225 */
226function nextHighestPowerOfTwo(x) {
227  --x;
228  for (var i = 1; i < 32; i <<= 1) {
229      x = x | x >> i;
230  }
231  return x + 1;
232}
233
234/**
235 * Represents a 2-dimensional size value. 
236 */
237var Size = (function size() {
238  function constructor(w, h) {
239    this.w = w;
240    this.h = h;
241  }
242  constructor.prototype = {
243    toString: function () {
244      return "(" + this.w + ", " + this.h + ")";
245    },
246    getNextHighestPowerOfTwo: function() {
247      return new Size(nextHighestPowerOfTwo(this.w), 
248                      nextHighestPowerOfTwo(this.h));
249    }
250  }
251  return constructor;
252})();
253
254/**
255 * Creates a new prototype object derived from another objects prototype along with a list of additional properties.
256 *
257 * @param base object whose prototype to use as the created prototype object's prototype
258 * @param properties additional properties to add to the created prototype object
259 */
260function inherit(base, properties) {
261  var prot = Object.create(base.prototype);
262  for (var p in properties) {
263    prot[p] = properties[p];
264  }
265  return prot;
266}