esprima
Version:
ECMAScript parsing infrastructure for multipurpose analysis
1,576 lines (1,453 loc) • 96.3 kB
JavaScript
/*!
* Benchmark.js <http://benchmarkjs.com/>
* Copyright 2010-2011 Mathias Bynens <http://mths.be/>
* Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
* Modified by John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit>
*/
;(function(window, undefined) {
/** Detect free variable `define` */
var freeDefine = typeof define == 'function' &&
typeof define.amd == 'object' && define.amd && define,
/** Detect free variable `exports` */
freeExports = typeof exports == 'object' && exports &&
(typeof global == 'object' && global && global == global.global && (window = global), exports),
/** Detect free variable `require` */
freeRequire = typeof require == 'function' && require,
/** Used to assign each benchmark an incrimented id */
counter = 0,
/** Used to crawl all properties regardless of enumerability */
getAllKeys = Object.getOwnPropertyNames,
/** Used to get property descriptors */
getDescriptor = Object.getOwnPropertyDescriptor,
/** Used in case an object doesn't have its own method */
hasOwnProperty = {}.hasOwnProperty,
/** Used to check if an object is extensible */
isExtensible = Object.isExtensible || function() { return true; },
/** Used to check if an own property is enumerable */
propertyIsEnumerable = {}.propertyIsEnumerable,
/** Used to set property descriptors */
setDescriptor = Object.defineProperty,
/** Used to resolve a value's internal [[Class]] */
toString = {}.toString,
/** Used to integrity check compiled tests */
uid = 'uid' + (+new Date),
/** Used to avoid infinite recursion when methods call each other */
calledBy = {},
/** Used to avoid hz of Infinity */
divisors = {
'1': 4096,
'2': 512,
'3': 64,
'4': 8,
'5': 0
},
/**
* T-Distribution two-tailed critical values for 95% confidence
* http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm
*/
distribution = {
'1': 12.706,'2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.447,
'7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.179,
'13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.101,
'19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.064,
'25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.042,
'infinity': 1.96
},
/** Used to flag environments/features */
has = {
/** Detect Adobe AIR */
'air': isClassOf(window.runtime, 'ScriptBridgingProxyObject'),
/** Detect if `arguments` objects have the correct internal [[Class]] value */
'argumentsClass': isClassOf(arguments, 'Arguments'),
/** Detect if strings support accessing characters by index */
'charByIndex':
// IE8 supports indexes on string literals but not string objects
Object('x')[0] == 'x',
/** Detect if strings have indexes as own properties */
'charByOwnIndex':
// Narwhal, Rhino, RingoJS, and Opera < 10.52 support indexes on strings
// but don't detect them as own properties
hasKey('x', '0'),
/** Detect if functions support decompilation */
'decompilation': !!(function() {
try{
// Safari 2.x removes commas in object literals
// from Function#toString results
// http://webk.it/11609
// Firefox 3.6 and Opera 9.25 strip grouping
// parentheses from Function#toString results
// http://bugzil.la/559438
return Function(
'return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 }; }) + ')'
)()(0).x === '1';
} catch(e) { }
}()),
/** Detect ES5+ property descriptor API */
'descriptors' : !!(function() {
try {
var o = {};
return (setDescriptor(o, o, o), 'value' in getDescriptor(o, o));
} catch(e) { }
}()),
/** Detect ES5+ Object.getOwnPropertyNames() */
'getAllKeys': !!(function() {
try {
return /\bvalueOf\b/.test(getAllKeys(Object.prototype));
} catch(e) { }
}()),
/** Detect if Java is enabled/exposed */
'java': isClassOf(window.java, 'JavaPackage'),
/** Detect if the Timers API exists */
'timeout': isHostType(window, 'setTimeout') && isHostType(window, 'clearTimeout')
},
/**
* Timer utility object used by `clock()` and `Deferred#resolve`.
* @private
* @type Object
*/
timer = {
/**
* The timer namespace object or constructor.
* @private
* @memberOf timer
* @type Function|Object
*/
'ns': Date,
/**
* Starts the deferred timer.
* @private
* @memberOf timer
* @param {Object} deferred The deferred instance.
*/
'start': null, // lazy defined in `clock()`
/**
* Stops the deferred timer.
* @private
* @memberOf timer
* @param {Object} deferred The deferred instance.
*/
'stop': null // lazy defined in `clock()`
},
/** Shortcut for inverse results */
noArgumentsClass = !has.argumentsClass,
noCharByIndex = !has.charByIndex,
noCharByOwnIndex = !has.charByOwnIndex,
/** Math shortcuts */
abs = Math.abs,
floor = Math.floor,
max = Math.max,
min = Math.min,
pow = Math.pow,
sqrt = Math.sqrt;
/*--------------------------------------------------------------------------*/
/**
* Benchmark constructor.
* @constructor
* @param {String} name A name to identify the benchmark.
* @param {Function|String} fn The test to benchmark.
* @param {Object} [options={}] Options object.
* @example
*
* // basic usage (the `new` operator is optional)
* var bench = new Benchmark(fn);
*
* // or using a name first
* var bench = new Benchmark('foo', fn);
*
* // or with options
* var bench = new Benchmark('foo', fn, {
*
* // displayed by Benchmark#toString if `name` is not available
* 'id': 'xyz',
*
* // called when the benchmark starts running
* 'onStart': onStart,
*
* // called after each run cycle
* 'onCycle': onCycle,
*
* // called when aborted
* 'onAbort': onAbort,
*
* // called when a test errors
* 'onError': onError,
*
* // called when reset
* 'onReset': onReset,
*
* // called when the benchmark completes running
* 'onComplete': onComplete,
*
* // compiled/called before the test loop
* 'setup': setup,
*
* // compiled/called after the test loop
* 'teardown': teardown
* });
*
* // or name and options
* var bench = new Benchmark('foo', {
*
* // a flag to indicate the benchmark is deferred
* 'deferred': true,
*
* // benchmark test function
* 'fn': function(deferred) {
* // call resolve() when the deferred test is finished
* deferred.resolve();
* }
* });
*
* // or options only
* var bench = new Benchmark({
*
* // benchmark name
* 'name': 'foo',
*
* // benchmark test as a string
* 'fn': '[1,2,3,4].sort()'
* });
*
* // a test's `this` binding is set to the benchmark instance
* var bench = new Benchmark('foo', function() {
* 'My name is '.concat(this.name); // My name is foo
* });
*/
function Benchmark(name, fn, options) {
var me = this;
// allow instance creation without the `new` operator
if (me && me.constructor != Benchmark) {
return new Benchmark(name, fn, options);
}
// juggle arguments
if (isClassOf(name, 'Object')) {
// 1 argument (options)
options = name;
}
else if (isClassOf(name, 'Function')) {
// 2 arguments (fn, options)
options = fn;
fn = name;
}
else if (isClassOf(fn, 'Object')) {
// 2 arguments (name, options)
options = fn;
fn = null;
me.name = name;
}
else {
// 3 arguments (name, fn [, options])
me.name = name;
}
setOptions(me, options);
me.id || (me.id = ++counter);
me.fn == null && (me.fn = fn);
me.stats = extend({}, me.stats);
me.times = extend({}, me.times);
}
/**
* Deferred constructor.
* @constructor
* @memberOf Benchmark
* @param {Object} bench The benchmark instance.
*/
function Deferred(bench) {
var me = this;
if (me && me.constructor != Deferred) {
return new Deferred(bench);
}
me.benchmark = bench;
clock(me);
}
/**
* Event constructor.
* @constructor
* @memberOf Benchmark
* @param {String|Object} type The event type.
*/
function Event(type) {
var me = this;
return (me && me.constructor != Event)
? new Event(type)
: (type instanceof Event)
? type
: extend(me, typeof type == 'string' ? { 'type': type } : type);
}
/**
* Suite constructor.
* @constructor
* @memberOf Benchmark
* @param {String} name A name to identify the suite.
* @param {Object} [options={}] Options object.
* @example
*
* // basic usage (the `new` operator is optional)
* var suite = new Benchmark.Suite;
*
* // or using a name first
* var suite = new Benchmark.Suite('foo');
*
* // or with options
* var suite = new Benchmark.Suite('foo', {
*
* // called when the suite starts running
* 'onStart': onStart,
*
* // called between running benchmarks
* 'onCycle': onCycle,
*
* // called when aborted
* 'onAbort': onAbort,
*
* // called when a test errors
* 'onError': onError,
*
* // called when reset
* 'onReset': onReset,
*
* // called when the suite completes running
* 'onComplete': onComplete
* });
*/
function Suite(name, options) {
var me = this;
// allow instance creation without the `new` operator
if (me && me.constructor != Suite) {
return new Suite(name, options);
}
// juggle arguments
if (isClassOf(name, 'Object')) {
// 1 argument (options)
options = name;
} else {
// 2 arguments (name [, options])
me.name = name;
}
setOptions(me, options);
}
/*--------------------------------------------------------------------------*/
/**
* Note: Some array methods have been implemented in plain JavaScript to avoid
* bugs in IE, Opera, Rhino, and Mobile Safari.
*
* IE compatibility mode and IE < 9 have buggy Array `shift()` and `splice()`
* functions that fail to remove the last element, `object[0]`, of
* array-like-objects even though the `length` property is set to `0`.
* The `shift()` method is buggy in IE 8 compatibility mode, while `splice()`
* is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9.
*
* In Opera < 9.50 and some older/beta Mobile Safari versions using `unshift()`
* generically to augment the `arguments` object will pave the value at index 0
* without incrimenting the other values's indexes.
* https://github.com/documentcloud/underscore/issues/9
*
* Rhino and environments it powers, like Narwhal and RingoJS, may have
* buggy Array `concat()`, `reverse()`, `shift()`, `slice()`, `splice()` and
* `unshift()` functions that make sparse arrays non-sparse by assigning the
* undefined indexes a value of undefined.
* https://github.com/mozilla/rhino/commit/702abfed3f8ca043b2636efd31c14ba7552603dd
*/
/**
* Creates an array containing the elements of the host array followed by the
* elements of each argument in order.
* @memberOf Benchmark.Suite
* @returns {Array} The new array.
*/
function concat() {
var value,
j = -1,
length = arguments.length,
result = slice.call(this),
index = result.length;
while (++j < length) {
value = arguments[j];
if (isClassOf(value, 'Array')) {
for (var k = 0, l = value.length; k < l; k++, index++) {
if (k in value) {
result[index] = value[k];
}
}
} else {
result[index] = value;
}
}
return result;
}
/**
* Utility function used by `shift()`, `splice()`, and `unshift()`.
* @private
* @param {Number} start The index to start inserting elements.
* @param {Number} deleteCount The number of elements to delete from the insert point.
* @param {Array} elements The elements to insert.
* @returns {Array} An array of deleted elements.
*/
function insert(start, deleteCount, elements) {
var deleteEnd = start + deleteCount,
elementCount = elements ? elements.length : 0,
index = start - 1,
length = start + elementCount,
object = this,
result = [],
tail = slice.call(object, deleteEnd);
// delete elements from the array
while (++index < deleteEnd) {
if (index in object) {
result[index - start] = object[index];
delete object[index];
}
}
// insert elements
index = start - 1;
while (++index < length) {
object[index] = elements[index - start];
}
// append tail elements
start = index--;
length = (object.length >>> 0) - deleteCount + elementCount;
while (++index < length) {
if ((index - start) in tail) {
object[index] = tail[index - start];
} else {
delete object[index];
}
}
// delete excess elements
deleteCount = deleteCount > elementCount ? deleteCount - elementCount : 0;
while (deleteCount--) {
delete object[length + deleteCount];
}
object.length = length;
return result;
}
/**
* Rearrange the host array's elements in reverse order.
* @memberOf Benchmark.Suite
* @returns {Array} The reversed array.
*/
function reverse() {
var upperIndex,
value,
index = -1,
object = Object(this),
length = object.length >>> 0,
middle = floor(length / 2);
if (length > 1) {
while (++index < middle) {
upperIndex = length - index - 1;
value = upperIndex in object ? object[upperIndex] : uid;
if (index in object) {
object[upperIndex] = object[index];
} else {
delete object[upperIndex];
}
if (value != uid) {
object[index] = value;
} else {
delete object[index];
}
}
}
return object;
}
/**
* Removes the first element of the host array and returns it.
* @memberOf Benchmark.Suite
* @returns {Mixed} The first element of the array.
*/
function shift() {
return insert.call(this, 0, 1)[0];
}
/**
* Creates an array of the host array's elements from the start index up to,
* but not including, the end index.
* @memberOf Benchmark.Suite
* @returns {Array} The new array.
*/
function slice(start, end) {
var index = -1,
object = Object(this),
length = object.length >>> 0,
result = [];
start = toInteger(start);
start = start < 0 ? max(length + start, 0) : min(start, length);
start--;
end = end == null ? length : toInteger(end);
end = end < 0 ? max(length + end, 0) : min(end, length);
while ((++index, ++start) < end) {
if (start in object) {
result[index] = object[start];
}
}
return result;
}
/**
* Allows removing a range of elements and/or inserting elements into the host array.
* @memberOf Benchmark.Suite
* @returns {Array} An array of removed elements.
*/
function splice(start, deleteCount) {
var object = Object(this),
length = object.length >>> 0;
start = toInteger(start);
start = start < 0 ? max(length + start, 0) : min(start, length);
deleteCount = min(max(toInteger(deleteCount), 0), length - start);
return insert.call(object, start, deleteCount, slice.call(arguments, 2));
}
/**
* Converts the specified `value` to an integer.
* @private
* @param {Mixed} value The value to convert.
* @returns {Number} The resulting integer.
*/
function toInteger(value) {
value = +value;
return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1);
}
/**
* Appends arguments to the host array.
* @memberOf Benchmark.Suite
* @returns {Number} The new length.
*/
function unshift() {
var object = Object(this);
insert.call(object, 0, 0, arguments);
return object.length;
}
/*--------------------------------------------------------------------------*/
/**
* Executes a function, associated with a benchmark, synchronously or asynchronously.
* @private
* @param {Object} options The options object.
*/
function call(options) {
options || (options = {});
var fn = options.fn;
(!options.async && fn || function() {
var bench = options.benchmark,
ids = bench._timerIds || (bench._timerIds = []),
index = ids.length;
// under normal use there should only be one id at any time per benchmark
ids.push(setTimeout(function() {
ids.splice(index, 1);
ids.length || delete bench._timerIds;
fn();
}, bench.delay * 1e3));
})();
}
/**
* Creates a function from the given arguments string and body.
* @private
* @param {String} args The comma separated function arguments.
* @param {String} body The function body.
* @returns {Function} The new function.
*/
function createFunction() {
// lazy defined to fork based on supported features
createFunction = function(args, body) {
var anchor = freeDefine ? define.amd : Benchmark,
prop = uid + 'createFunction';
runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}');
return [anchor[prop], delete anchor[prop]][0];
};
// fix JaegerMonkey bug
// http://bugzil.la/639720
createFunction = (createFunction('', 'return"' + uid + '"') || noop)() == uid ? createFunction : Function;
return createFunction.apply(null, arguments);
}
/**
* Iterates over an object's properties, executing the `callback` for each.
* Callbacks may terminate the loop by explicitly returning `false`.
* @private
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
* @param {Object} options The options object.
* @returns {Object} Returns the object iterated over.
*/
function forProps() {
var forShadowed,
skipSeen,
forArgs = true,
shadowed = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'];
(function(enumFlag, key) {
// must use a non-native constructor to catch the Safari 2 issue
function Klass() { this.valueOf = 0; };
Klass.prototype.valueOf = 0;
// check various for..in bugs
for (key in new Klass) {
enumFlag += key == 'valueOf' ? 1 : 0;
}
// check if `arguments` objects have non-enumerable indexes
for (key in arguments) {
key == '0' && (forArgs = false);
}
// Safari 2 iterates over shadowed properties twice
// http://replay.waybackmachine.org/20090428222941/http://tobielangel.com/2007/1/29/for-in-loop-broken-in-safari/
skipSeen = enumFlag == 2;
// IE < 9 incorrectly makes an object's properties non-enumerable if they have
// the same name as other non-enumerable properties in its prototype chain.
forShadowed = !enumFlag;
}(0));
// lazy define
forProps = function(object, callback, options) {
options || (options = {});
var ctor,
key,
keys,
skipCtor,
done = !object,
result = [object, object = Object(object)][0],
which = options.which,
allFlag = which == 'all',
fn = callback,
index = -1,
iteratee = object,
length = object.length,
ownFlag = allFlag || which == 'own',
seen = {},
skipProto = isClassOf(object, 'Function'),
thisArg = options.bind;
object = Object(object);
if (thisArg !== undefined) {
callback = function(value, key, object) {
return fn.call(thisArg, value, key, object);
};
}
// iterate all properties
if (allFlag && has.getAllKeys) {
for (index = 0, keys = getAllKeys(object), length = keys.length; index < length; index++) {
key = keys[index];
if (callback(object[key], key, object) === false) {
break;
}
}
}
// else iterate only enumerable properties
else {
for (key in object) {
// Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
// (if the prototype or a property on the prototype has been set)
// incorrectly set a function's `prototype` property [[Enumerable]] value
// to `true`. Because of this we standardize on skipping the `prototype`
// property of functions regardless of their [[Enumerable]] value.
if ((done =
!(skipProto && key == 'prototype') &&
!(skipSeen && (hasKey(seen, key) || !(seen[key] = true))) &&
(!ownFlag || ownFlag && hasKey(object, key)) &&
callback(object[key], key, object) === false)) {
break;
}
}
// in IE < 9 strings don't support accessing characters by index
if (!done && (
forArgs && isArguments(object) ||
(noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'))) {
noCharByIndex && (iteratee = object.split(''));
while (++index < length) {
if ((done =
callback(iteratee[index], String(index), object) === false)) {
break;
}
}
}
if (!done && forShadowed) {
// Because IE < 9 can't set the `[[Enumerable]]` attribute of an existing
// property and the `constructor` property of a prototype defaults to
// non-enumerable, we manually skip the `constructor` property when we
// think we are iterating over a `prototype` object.
ctor = object.constructor;
skipCtor = ctor && ctor.prototype && ctor.prototype.constructor === ctor;
for (index = 0; index < 7; index++) {
key = shadowed[index];
if (!(skipCtor && key == 'constructor') &&
hasKey(object, key) &&
callback(object[key], key, object) === false) {
break;
}
}
}
}
return result;
};
return forProps.apply(null, arguments);
}
/**
* Gets the critical value for the specified degrees of freedom.
* @private
* @param {Number} df The degrees of freedom.
* @returns {Number} The critical value.
*/
function getCriticalValue(df) {
return distribution[Math.round(df) || 1] || distribution.infinity;
}
/**
* Gets the name of the first argument from a function's source.
* @private
* @param {Function} fn The function.
* @param {String} altName A string used when the name of the first argument is unretrievable.
* @returns {String} The argument name.
*/
function getFirstArgument(fn, altName) {
return (!hasKey(fn, 'toString') &&
(/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || altName || '';
}
/**
* Computes the arithmetic mean of a sample.
* @private
* @param {Array} sample The sample.
* @returns {Number} The mean.
*/
function getMean(sample) {
return reduce(sample, function(sum, x) {
return sum + x;
}, 0) / sample.length || 0;
}
/**
* Gets the source code of a function.
* @private
* @param {Function} fn The function.
* @param {String} altSource A string used when a function's source code is unretrievable.
* @returns {String} The function's source code.
*/
function getSource(fn, altSource) {
var result = altSource;
if (isStringable(fn)) {
result = String(fn);
} else if (has.decompilation) {
result = (/^[^{]+{([\s\S]*)}\s*$/.exec(fn) || 0)[1];
}
return (result || '').replace(/^\s+|\s+$/g, '');
}
/**
* Modify a string by replacing named tokens with matching object property values.
* @private
* @param {String} string The string to modify.
* @param {Object} object The template object.
* @returns {String} The modified string.
*/
function interpolate(string, object) {
forOwn(object, function(value, key) {
string = string.replace(RegExp('#\\{' + key + '\\}', 'g'), value);
});
return string;
}
/**
* Checks if a value is an `arguments` object.
* @private
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the value is an `arguments` object, else `false`.
*/
function isArguments() {
// lazy define
isArguments = function(value) {
return toString.call(value) == '[object Arguments]';
};
if (noArgumentsClass) {
isArguments = function(value) {
return hasKey(value, 'callee') &&
!(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee'));
};
}
return isArguments(arguments[0]);
}
/**
* Checks if an object is of the specified class.
* @private
* @param {Mixed} value The value to check.
* @param {String} name The name of the class.
* @returns {Boolean} Returns `true` if the value is of the specified class, else `false`.
*/
function isClassOf(value, name) {
return value != null && toString.call(value) == '[object ' + name + ']';
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of object, function, or unknown.
* @private
* @param {Mixed} object The owner of the property.
* @param {String} property The property to check.
* @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
var type = object != null ? typeof object[property] : 'number';
return !/^(?:boolean|number|string|undefined)$/.test(type) &&
(type == 'object' ? !!object[property] : true);
}
/**
* Checks if the specified `value` is an object created by the `Object` constructor.
* @private
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if `value` is an object, else `false`.
*/
function isObject(value) {
var ctor,
result = !!value && toString.call(value) == '[object Object]';
if (result && noArgumentsClass) {
// avoid false positives for `arguments` objects in IE < 9
result = !isArguments(value);
}
if (result) {
// IE < 9 presents nodes like `Object` objects:
// IE < 8 are missing the node's constructor property
// IE 8 node constructors are typeof "object"
ctor = value.constructor;
// check if the constructor is `Object` as `Object instanceof Object` is `true`
if ((result = isClassOf(ctor, 'Function') && ctor instanceof ctor)) {
// assume objects created by the `Object` constructor have no inherited enumerable properties
// (we assume there are no `Object.prototype` extensions)
forProps(value, function(subValue, subKey) {
result = subKey;
});
// An object's own properties are iterated before inherited properties.
// If the last iterated key belongs to an object's own property then
// there are no inherited enumerable properties.
result = result === true || hasKey(value, result);
}
}
return result;
}
/**
* Checks if a value can be safely coerced to a string.
* @private
* @param {Mixed} value The value to check.
* @returns {Boolean} Returns `true` if the value can be coerced, else `false`.
*/
function isStringable(value) {
return hasKey(value, 'toString') || isClassOf(value, 'String');
}
/**
* Wraps a function and passes `this` to the original function as the first argument.
* @private
* @param {Function} fn The function to be wrapped.
* @returns {Function} The new function.
*/
function methodize(fn) {
return function() {
var args = [this];
args.push.apply(args, arguments);
return fn.apply(null, args);
};
}
/**
* A no-operation function.
* @private
*/
function noop() {
// no operation performed
}
/**
* A wrapper around require() to suppress `module missing` errors.
* @private
* @param {String} id The module id.
* @returns {Mixed} The exported module or `null`.
*/
function req(id) {
try {
return freeExports && freeRequire(id);
} catch(e) { }
return null;
}
/**
* Runs a snippet of JavaScript via script injection.
* @private
* @param {String} code The code to run.
*/
function runScript(code) {
var parent,
script,
sibling,
anchor = freeDefine ? define.amd : Benchmark,
prop = uid + 'runScript',
prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();';
// Non-browser environments, Firefox 2.0.0.2 (executes asynchronously),
// and IE < 9 will error here and that's OK.
// Script injection is only used to avoid the previously commented JaegerMonkey bug.
// We remove the inserted script *before* running the code to avoid differences
// in the expected script element count/order of the document.
try {
sibling = document.getElementsByTagName('script')[0];
parent = sibling.parentNode;
script = document.createElement('script');
anchor[prop] = function() { parent.removeChild(script); };
script.appendChild(document.createTextNode(prefix + code));
parent.insertBefore(script, sibling);
} catch(e) { }
delete anchor[prop];
}
/**
* A helper function for setting options/event handlers.
* @private
* @param {Object} bench The benchmark instance.
* @param {Object} [options={}] Options object.
*/
function setOptions(bench, options) {
options = extend({}, bench.constructor.options, options);
bench.options = forOwn(options, function(value, key) {
if (value != null) {
// add event listeners
if (/^on[A-Z]/.test(key)) {
forEach(key.split(' '), function(key) {
bench.on(key.slice(2).toLowerCase(), value);
});
} else {
bench[key] = deepClone(value);
}
}
});
}
/*--------------------------------------------------------------------------*/
/**
* Handles cycling/completing the deferred benchmark.
* @memberOf Benchmark.Deferred
*/
function resolve() {
var me = this,
bench = me.benchmark;
if (++me.cycles < bench.count) {
(bench._host || bench).compiled.call(me, timer.ns, timer);
} else {
timer.stop(me);
call({
'async': true,
'benchmark': bench,
'fn': function() {
cycle({ 'benchmark': bench, 'deferred': me });
}
});
}
}
/*--------------------------------------------------------------------------*/
/**
* A deep clone utility.
* @static
* @memberOf Benchmark
* @param {Mixed} value The value to clone.
* @returns {Mixed} The cloned value.
*/
function deepClone(value) {
var accessor,
circular,
clone,
ctor,
data,
descriptor,
extensible,
key,
length,
markerKey,
parent,
result,
source,
subIndex,
index = -1,
marked = [],
unmarked = [],
queue = { '0': { 'value': value }, 'length': 1 };
/**
* An easily detectable decorator for cloned values.
*/
function Marker(object) {
this.raw = object;
}
/**
* Gets an available marker key for the given object.
*/
function getMarkerKey(object) {
// avoid collisions with existing keys
var result = uid;
while (object[result] && object[result].constructor != Marker) {
result += 1;
}
return result;
}
/**
* The callback used by `forProps()`.
*/
function propCallback(subValue, subKey) {
// exit early to avoid cloning the marker
if (subValue && subValue.constructor == Marker) {
return;
}
// add objects to the queue
if (subValue === Object(subValue)) {
queue[queue.length++] = { 'key': subKey, 'parent': clone, 'source': value };
}
// assign non-objects
else {
clone[subKey] = subValue;
}
}
while ((data = queue[++index])) {
key = data.key;
parent = data.parent;
source = data.source;
clone = value = source ? source[key] : data.value;
accessor = circular = descriptor = false;
delete queue[index - 1];
// create a basic clone to filter out functions, DOM elements, and
// other non `Object` objects
if (value === Object(value)) {
ctor = value.constructor;
switch (toString.call(value)) {
case '[object Array]':
clone = new ctor(value.length);
break;
case '[object Boolean]':
clone = new ctor(value == true);
break;
case '[object Date]':
clone = new ctor(+value);
break;
case '[object Object]':
isObject(value) && (clone = new ctor);
break;
case '[object Number]':
case '[object String]':
clone = new ctor(value);
break;
case '[object RegExp]':
clone = ctor(value.source,
(value.global ? 'g' : '') +
(value.ignoreCase ? 'i' : '') +
(value.multiline ? 'm' : ''));
}
// continue clone if `value` doesn't have an accessor descriptor
// http://es5.github.com/#x8.10.1
if (clone != value &&
!(descriptor = source && has.descriptors && getDescriptor(source, key),
accessor = descriptor && (descriptor.get || descriptor.set))) {
// use an existing clone (circular reference)
if ((extensible = isExtensible(value))) {
markerKey = getMarkerKey(value);
if (value[markerKey]) {
circular = clone = value[markerKey].raw;
}
} else {
// for frozen/sealed objects
for (subIndex = 0, length = unmarked.length; subIndex < length; subIndex++) {
data = unmarked[subIndex];
if (data.object === value) {
circular = clone = data.clone;
break;
}
}
}
if (!circular) {
// mark object to allow quickly detecting circular references and tie it to its clone
if (extensible) {
value[markerKey] = new Marker(clone);
marked.push({ 'key': markerKey, 'object': value });
} else {
// for frozen/sealed objects
unmarked.push({ 'clone': clone, 'object': value });
}
// iterate over object properties
forProps(value, propCallback, { 'which': 'all' });
}
}
}
if (parent) {
// for custom property descriptors
if (accessor || (descriptor &&
!(descriptor.configurable && descriptor.enumerable && descriptor.writable))) {
descriptor.value && (descriptor.value = clone);
setDescriptor(parent, key, descriptor);
}
// for default property descriptors
else {
parent[key] = clone;
}
} else {
result = clone;
}
}
// remove markers
for (index = 0, length = marked.length; index < length; index++) {
data = marked[index];
delete data.object[data.key];
}
return result;
}
/**
* An iteration utility for arrays and objects.
* Callbacks may terminate the loop by explicitly returning `false`.
* @static
* @memberOf Benchmark
* @param {Array|Object} object The object to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Object} thisArg The `this` binding for the callback function.
* @returns {Array|Object} Returns the object iterated over.
*/
function each(object, callback, thisArg) {
var fn = callback,
index = -1,
result = [object, object = Object(object)][0],
origObject = object,
length = object.length,
isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)),
isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'),
isConvertable = isSnapshot || isSplittable || 'item' in object;
// in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists
if (length === length >>> 0) {
if (isConvertable) {
// the third argument of the callback is the original non-array object
callback = function(value, index) {
return fn.call(this, value, index, origObject);
};
// in IE < 9 strings don't support accessing characters by index
if (isSplittable) {
object = object.split('');
} else {
object = [];
while (++index < length) {
// in Safari 2 `index in object` is always `false` for NodeLists
object[index] = isSnapshot ? result.snapshotItem(index) : result[index];
}
}
}
forEach(object, callback, thisArg);
} else {
forOwn(object, callback, thisArg);
}
return result;
}
/**
* Copies own/inherited properties of a source object to the destination object.
* @static
* @memberOf Benchmark
* @param {Object} destination The destination object.
* @param {Object} [source={}] The source object.
* @returns {Object} The destination object.
*/
function extend(destination, source) {
// Chrome < 14 incorrectly sets `destination` to `undefined` when we `delete arguments[0]`
// http://code.google.com/p/v8/issues/detail?id=839
destination = [destination, delete arguments[0]][0];
forEach(arguments, function(source) {
forProps(source, function(value, key) {
destination[key] = value;
});
});
return destination;
}
/**
* A generic `Array#filter` like method.
* @static
* @memberOf Benchmark
* @param {Array} array The array to iterate over.
* @param {Function|String} callback The function/alias called per iteration.
* @param {Object} thisArg The `this` binding for the callback function.
* @returns {Array} A new array of values that passed callback filter.
* @example
*
* // get odd numbers
* Benchmark.filter([1, 2, 3, 4, 5], function(n) {
* return n % 2;
* }); // -> [1, 3, 5];
*
* // get fastest benchmarks
* Benchmark.filter(benches, 'fastest');
*
* // get slowest benchmarks
* Benchmark.filter(benches, 'slowest');
*
* // get benchmarks that completed without erroring
* Benchmark.filter(benches, 'successful');
*/
function filter(array, callback, thisArg) {
var result;
if (callback == 'successful') {
// callback to exclude errored or unrun benchmarks
callback = function(bench) { return bench.cycles; };
}
else if (callback == 'fastest' || callback == 'slowest') {
// get successful, sort by period + margin of error, and filter fastest/slowest
result = filter(array, 'successful').sort(function(a, b) {
a = a.stats; b = b.stats;
return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback == 'fastest' ? 1 : -1);
});
result = filter(result, function(bench) {
return !result[0].compare(bench);
});
}
return result || reduce(array, function(result, value, index) {
return callback.call(thisArg, value, index, array) ? (result.push(value), result) : result;
}, []);
}
/**
* A generic `Array#forEach` like method.
* Callbacks may terminate the loop by explicitly returning `false`.
* @static
* @memberOf Benchmark
* @param {Array} array The array to iterate over.
* @param {Function} callback The function called per iteration.
* @param {Object} thisArg The `this` binding for the callback function.
* @returns {Array} Returns the array iterated over.
*/
function forEach(array, callback, thisArg) {
var fn = callback,
index = -1,
length = (array = Object(array)).length >>> 0;
if (thisArg !== undefined) {
callback = function(value, index, array) {
return fn.call(thisArg, value, index, array);
};
}
while (++index < length) {
if (index in array &&
callback(array[index], index, array) === false) {
break;
}
}
return array;
}
/**
* Iterates over an object's own properties, executing the `callback` for each.
* Callbacks may terminate the loop by explicitly returning `false`.
* @static
* @memberOf Benchmark
* @param {Object} object The object to iterate over.
* @param {Function} callback The function executed per own property.
* @param {Object} thisArg The `this` binding for the callback function.
* @returns {Object} Returns the object iterated over.
*/
function forOwn(object, callback, thisArg) {
return forProps(object, callback, { 'bind': thisArg, 'which': 'own' });
}
/**
* Converts a number to a more readable comma-separated string representation.
* @static
* @memberOf Benchmark
* @param {Number} number The number to convert.
* @returns {String} The more readable string representation.
*/
function formatNumber(number) {
number = String(number).split('.');
return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') +
(number[1] ? '.' + number[1] : '');
}
/**
* Checks if an object has the specified key as a direct property.
* @static
* @memberOf Benchmark
* @param {Object} object The object to check.
* @param {String} key The key to check for.
* @returns {Boolean} Returns `true` if key is a direct property, else `false`.
*/
function hasKey() {
// lazy define for worst case fallback (not as accurate)
hasKey = function(object, key) {
var parent = object != null && (object.constructor || Object).prototype;
return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]);
};
// for modern browsers
if (isClassOf(hasOwnProperty, 'Function')) {
hasKey = function(object, key) {
return object != null && hasOwnProperty.call(object, key);
};
}
// for Safari 2
else if ({}.__proto__ == Object.prototype) {
hasKey = function(object, key) {
var result = false;
if (object != null) {
object = Object(object);
object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0];
}
return result;
};
}
return hasKey.apply(this, arguments);
}
/**
* A generic `Array#indexOf` like method.
* @static
* @memberOf Benchmark
* @param {Array} array The array to iterate over.
* @param {Mixed} value The value to search for.
* @param {Number} [fromIndex=0] The index to start searching from.
* @returns {Number} The index of the matched value or `-1`.
*/
function indexOf(array, value, fromIndex) {
var index = toInteger(fromIndex),
length = (array = Object(array)).length >>> 0;
index = (index < 0 ? max(0, length + index) : index) - 1;
while (++index < length) {
if (index in array && value === array[index]) {
return index;
}
}
return -1;
}
/**
* Invokes a method on all items in an array.
* @static
* @memberOf Benchmark
* @param {Array} benches Array of benchmarks to iterate over.
* @param {String|Object} name The name of the method to invoke OR options object.
* @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with.
* @returns {Array} A new array of values returned from each method invoked.
* @example
*
* // invoke `reset` on all benchmarks
* Benchmark.invoke(benches, 'reset');
*
* // invoke `emit` with arguments
* Benchmark.invoke(benches, 'emit', 'complete', listener);
*
* // invoke `run(true)`, treat benchmarks as a queue, and register invoke callbacks
* Benchmark.invoke(benches, {
*
* // invoke the `run` method
* 'name': 'run',
*
* // pass a single argument
* 'args': true,
*
* // treat as queue, removing benchmarks from front of `benches` until empty
* 'queued': true,
*
* // called before any benchmarks have been invoked.
* 'onStart': onStart,
*
* // called between invoking benchmarks
* 'onCycle': onCycle,
*
* // called after all benchmarks have been invoked.
* 'onComplete': onComplete
* });
*/
function invoke(benches, name) {
var args,
bench,
queued,
index = -1,
options = { 'onStart': noop, 'onCycle': noop, 'onComplete': noop },
result = map(benches, function(bench) { return bench; });
/**
* Checks if invoking `run` with asynchronous cycles.
*/
function isAsync(object) {
var async = args[0] && args[0].async;
return isRun(object) && (async == null ? object.options.async : async) && has.timeout;
}
/**
* Checks if invoking `run` on a benchmark instance.
*/
function isRun(object) {
// avoid using `instanceof` here because of IE memory leak issues with host objects
return Object(object).constructor == Benchmark && name == 'run';
}
/**
* Checks if invoking `run` with synchronous cycles.
*/
function isSync(object) {
// if not asynchronous or deferred
return !isAsync(object) && !(isRun(object) && object.defer);
}
/**
* Executes the method and if synchronous, fetches the next bench.
*/
function execute() {
var listeners,
sync = isSync(bench);
if (!sync) {
// use `getNext` as a listener
bench.on('complete', getNext);
listeners = bench.events.complete;
listeners.splice(0, 0, listeners.pop());
}
// execute method
result[index] = isClassOf(bench && bench[name], 'Function') ? bench[name].apply(bench, args) : undefined;
// if synchronous return true until finished
return sync && getNext();
}
/**
* Fetches the next bench or executes `onComplete` callback.
*/
function getNext() {
var last = bench,
sync = isSync(last);
if (!sync) {
last.removeListener('complete', getNext);
last.emit('complete');
}
// choose next benchmark if not exiting early
if (options.onCycle.call(benches, Event('cycle'), last) !== false && raiseIndex() !== false) {
bench = queued ? benches[0] : result[index];
if (!isSync(bench)) {
call({ 'async': isAsync(bench), 'benchmark': bench, 'fn': execute });
}
else if (!sync) {
// resume synchronous execution
while (execute()) { }
}
else {
// continue synchronous execution
return true;
}
} else {
options.onComplete.call(benches, Event('complete'), last);
}
// when async the `return false` will cancel the rest of the "complete"
// listeners because they were called above and when synchronous it will
// exit the while-loop
return false;
}
/**
* Raises `index` to the next defined index or returns `false`.
*/
function raiseIndex() {
var length = result.length;
// if queued then remove the previous bench and subsequent skipped non-entries
if (queued) {
do {
++index > 0 && shift.call(benches);
} while ((length = benches.length) && !('0' in benches));
}
else {
while (++index < length && !(index in result)) { }
}
// if we reached the last index then return `false`
return (queued ? length : index < length) ? index : (index = false);
}
// juggle arguments
if (isClassOf(name, 'String')) {
// 2 arguments (array, name)
args = slice.call(arguments, 2);
} else {
// 2 arguments (array, options)
options = extend(options, name);
name = options.name;
args = isClassOf(args = 'args' in options ? options.args : [], 'Array') ? args : [args];
queued = options.queued;
}
// start iterating over the array
if (raiseIndex() !== false) {
bench = result[index];
options.onStart.call(benches, Event('start'), bench);
// end early if the suite was aborted in an "onStart" listener
if (benches.aborted && benches.constructor == Suite && name == 'run') {
options.onCycle.call(benches, Event('cycle'), bench);
options.onComplete.call(benches, Event('complete'), bench);
}
// else start
else {
if (isAsync(bench)) {
call({ 'async': true, 'benchmark': bench, 'fn': execute });
} else {
while (execute()) { }
}
}
}
return result;
}
/**
* Creates a string of joined array values or object key-value pairs.
* @static
* @memberOf Benchmark
* @param {Array|Object} object The object to operate on.
* @param {String} [separator1=','] The separator used between key-value pairs.
* @param {String} [separator2=': '] The separator used between keys and values.
* @re