Add es5-shim v2.0.2 in order to fix IE8 / IE7 compatibility.

See:
- discussion on mailing-list: https://groups.google.com/d/topic/amber-lang/EOlsvFd5ynk/discussion
- es5-shim: https://github.com/kriskowal/es5-shim/
This commit is contained in:
Laurent Laffont 2012-11-07 11:46:23 +01:00
parent 7de4a20e58
commit 09fc6dab27
27 changed files with 6634 additions and 23 deletions

View File

@ -56,7 +56,8 @@ amber = (function() {
}
loadDependencies();
addJSToLoad('compat.js');
addJSToLoad('lib/es5-shim-2.0.2/es5-shim.min.js');
addJSToLoad('lib/es5-shim-2.0.2/es5-sham.min.js');
addJSToLoad('boot.js');
if (deploy) {

View File

@ -1,22 +0,0 @@
/* IE<9 does not have Array.indexOf , needed for amber */
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/)
{
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++)
{
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}

2
js/lib/es5-shim-2.0.2/.gitignore vendored Executable file
View File

@ -0,0 +1,2 @@
node_modules
.DS_Store

93
js/lib/es5-shim-2.0.2/CHANGES Executable file
View File

@ -0,0 +1,93 @@
2.0.0
- Separate reliable shims from dubious shims (shams).
1.2.10
- Group-effort Style Cleanup
- Took a stab at fixing Object.defineProperty on IE8 without
bad side-effects. (@hax)
- Object.isExtensible no longer fakes it. (@xavierm)
- Date.prototype.toISOString no longer deals with partial
ISO dates, per spec (@kitcambridge)
- More (mostly from @bryanforbes)
1.2.9
- Corrections to toISOString by @kitcambridge
- Fixed three bugs in array methods revealed by Jasmine tests.
- Cleaned up Function.prototype.bind with more fixes and tests from
@bryanforbes.
1.2.8
- Actually fixed problems with Function.prototype.bind, and regressions
from 1.2.7 (@bryanforbes, @jdalton #36)
1.2.7 - REGRESSED
- Fixed problems with Function.prototype.bind when called as a constructor.
(@jdalton #36)
1.2.6
- Revised Date.parse to match ES 5.1 (kitcambridge)
1.2.5
- Fixed a bug for padding it Date..toISOString (tadfisher issue #33)
1.2.4
- Fixed a descriptor bug in Object.defineProperty (raynos)
1.2.3
- Cleaned up RequireJS and <script> boilerplate
1.2.2
- Changed reduce to follow the letter of the spec with regard to having and
owning properties.
- Fixed a bug where RegExps pass as Functions in some engines in reduce.
1.2.1
- Adding few fixes to make jshint happy.
- Fix for issue #12, function expressions can cause scoping issues in IE.
- NPM will minify on install or when `npm run-script install` is executed.
- Adding .gitignore to avoid publishing dev dependencies.
1.2.0
- Making script loadable as AMD module.
- Adding `indexOf` to the list of safe shims.
1.1.0
- Added support for accessor properties where possible (which is all browsers
except IE).
- Stop exposing bound function's (that are returned by
`Function.prototype.bind`) internal properties (`bound, boundTo, boundArgs`)
as in some cases (when using facade objects for example) capabilities of the
enclosed functions will be leaked.
- `Object.create` now explicitly sets `__proto__` property to guarantee
correct behavior of `Object.getPrototypeOf`'s on all objects created using
`Object.create`.
- Switched to `===` from `==` where possible as it's slightly faster on older
browsers that are target of this lib.
- Added names to all anonymous functions to have a better stack traces.
1.0.0
- fixed Date.toISODate, using UTC accessors, as in
http://code.google.com/p/v8/source/browse/trunk/src/date.js?r=6120#986
(arian)
0.0.4
- Revised Object.getPrototypeOf to work in more cases
in response to http://ejohn.org/blog/objectgetprototypeof/
[issue #2] (fschaefer)
0.0.3
- Fixed typos in Object.keys (samsonjs)
0.0.2
Per kangax's recommendations:
- faster Object.create(null)
- fixed a function-scope function declaration statement in Object.create
0.0.1
- fixed Object.create(null), in so far as that's possible
- reworked Rhino Object.freeze(Function) bug detector and patcher
0.0.0
- forked from narwhal-lib

View File

@ -0,0 +1,25 @@
- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License
- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal
Project)
- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA
- fschaefer Florian Schäfer Copyright (C) 2010 MIT License
- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License
- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License
- kossnocorp Sasha Koss XXX TODO License or CLA
- bryanforbes Bryan Forbes XXX TODO License or CLA
- killdream Quildreen Motta Copyright (C) 2011 MIT Licence
- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD
License
- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License
- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain)
- iwyg XXX TODO License or CLA
- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License
- xavierm02 Montillet Xavier Copyright (C) 2011 MIT License
- Raynos Jake Verbaten Copyright (C) 2011 MIT Licence
- samsonjs Sami Samhuri Copyright (C) 2010 MIT License
- rwldrn Rick Waldron Copyright (C) 2011 MIT License
- lexer Alexey Zakharov XXX TODO License or CLA
- 280 North Inc. (Now Motorola LLC, a subsidiary of Google Inc.)
Copyright (C) 2009 MIT License

19
js/lib/es5-shim-2.0.2/LICENSE Executable file
View File

@ -0,0 +1,19 @@
Copyright 2009, 2010 Kristopher Michael Kowal. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

161
js/lib/es5-shim-2.0.2/README.md Executable file
View File

@ -0,0 +1,161 @@
`es5-shim.js` and `es5-shim.min.js` monkey-patch a JavaScript context to
contain all EcmaScript 5 methods that can be faithfully emulated with a
legacy JavaScript engine.
`es5-sham.js` and `es5-sham.min.js` monkey-patch other ES5 methods as
closely as possible. For these methods, as closely as possible to ES5
is not very close. Many of these shams are intended only to allow code
to be written to ES5 without causing run-time errors in older engines.
In many cases, this means that these shams cause many ES5 methods to
silently fail. Decide carefully whether this is what you want.
## Tests
The tests are written with the Jasmine BDD test framework.
To run the tests, navigate to <root-folder>/tests/.
In order to run against the shim-code, the tests attempt to kill the current
implementation of the missing methods. This happens in <root-folder>/tests/helpers/h-kill.js.
So in order to run the tests against the build-in methods, invalidate that file somehow
(comment-out, delete the file, delete the script-tag, etc.).
## Shims
### Complete tests ###
* Array.prototype.every
* Array.prototype.filter
* Array.prototype.forEach
* Array.prototype.indexOf
* Array.prototype.lastIndexOf
* Array.prototype.map
* Array.prototype.some
* Array.prototype.reduce
* Array.prototype.reduceRight
* Array.isArray
* Date.now
* Date.prototype.toJSON
* Function.prototype.bind
* /!\ Caveat: the bound function's length is always 0.
* /!\ Caveat: the bound function has a prototype property.
* /!\ Caveat: bound functions do not try too hard to keep you
from manipulating their ``arguments`` and ``caller`` properties.
* /!\ Caveat: bound functions don't have checks in ``call`` and
``apply`` to avoid executing as a constructor.
* Object.keys
* String.prototype.trim
### Untested ###
* Date.parse (for ISO parsing)
* Date.prototype.toISOString
## Shams
* /?\ Object.create
For the case of simply "begetting" an object that
inherits prototypically from another, this should work
fine across legacy engines.
/!\ Object.create(null) will work only in browsers that
support prototype assignment. This creates an object
that does not have any properties inherited from
Object.prototype. It will silently fail otherwise.
/!\ The second argument is passed to
Object.defineProperties which will probably fail
silently.
* /?\ Object.getPrototypeOf
This will return "undefined" in some cases. It uses
__proto__ if it's available. Failing that, it uses
constructor.prototype, which depends on the constructor
property of the object's prototype having not been
replaced. If your object was created like this, it
won't work:
function Foo() {
}
Foo.prototype = {};
Because the prototype reassignment destroys the
constructor property.
This will work for all objects that were created using
`Object.create` implemented with this library.
* /!\ Object.getOwnPropertyNames
This method uses Object.keys, so it will not be accurate
on legacy engines.
* Object.isSealed
Returns "false" in all legacy engines for all objects,
which is conveniently guaranteed to be accurate.
* Object.isFrozen
Returns "false" in all legacy engines for all objects,
which is conveniently guaranteed to be accurate.
* Object.isExtensible
Works like a charm, by trying very hard to extend the
object then redacting the extension.
### Fail silently
* /!\ Object.getOwnPropertyDescriptor
The behavior of this shim does not conform to ES5. It
should probably not be used at this time, until its
behavior has been reviewed and been confirmed to be
useful in legacy engines.
* /!\ Object.defineProperty
This method will silently fail to set "writable",
"enumerable", and "configurable" properties.
Providing a getter or setter with "get" or "set" on a
descriptor will silently fail on engines that lack
"__defineGetter__" and "__defineSetter__", which include
all versions of IE up to version 8 so far.
IE 8 provides a version of this method but it only works
on DOM objects. Thus, the shim will not get installed
and attempts to set "value" properties will fail
silently on non-DOM objects.
https://github.com/kriskowal/es5-shim/issues#issue/5
* /!\ Object.defineProperties
This uses the Object.defineProperty shim
* Object.seal
Silently fails on all legacy engines. This should be
fine unless you are depending on the safety and security
provisions of this method, which you cannot possibly
obtain in legacy engines.
* Object.freeze
Silently fails on all legacy engines. This should be
fine unless you are depending on the safety and security
provisions of this method, which you cannot possibly
obtain in legacy engines.
* Object.preventExtensions
Silently fails on all legacy engines. This should be
fine unless you are depending on the safety and security
provisions of this method, which you cannot possibly
obtain in legacy engines.

335
js/lib/es5-shim-2.0.2/es5-sham.js Executable file
View File

@ -0,0 +1,335 @@
// Copyright 2009-2012 by contributors, MIT License
// vim: ts=4 sts=4 sw=4 expandtab
// Module systems magic dance
(function (definition) {
// RequireJS
if (typeof define == "function") {
define(definition);
// YUI3
} else if (typeof YUI == "function") {
YUI.add("es5-sham", definition);
// CommonJS and <script>
} else {
definition();
}
})(function () {
// ES5 15.2.3.2
// http://es5.github.com/#x15.2.3.2
if (!Object.getPrototypeOf) {
// https://github.com/kriskowal/es5-shim/issues#issue/2
// http://ejohn.org/blog/objectgetprototypeof/
// recommended by fschaefer on github
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__ || (
object.constructor
? object.constructor.prototype
: prototypeOfObject
);
};
}
// ES5 15.2.3.3
// http://es5.github.com/#x15.2.3.3
if (!Object.getOwnPropertyDescriptor) {
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a non-object: ";
Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
if ((typeof object != "object" && typeof object != "function") || object === null) {
throw new TypeError(ERR_NON_OBJECT + object);
}
// If object does not owns property return undefined immediately.
if (!owns(object, property)) {
return;
}
// If object has a property then it's for sure both `enumerable` and
// `configurable`.
var descriptor = { enumerable: true, configurable: true };
// If JS engine supports accessor properties then property may be a
// getter or setter.
if (supportsAccessors) {
// Unfortunately `__lookupGetter__` will return a getter even
// if object has own non getter property along with a same named
// inherited getter. To avoid misbehavior we temporary remove
// `__proto__` so that `__lookupGetter__` will return getter only
// if it's owned by an object.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
// Once we have getter and setter we can put values back.
object.__proto__ = prototype;
if (getter || setter) {
if (getter) {
descriptor.get = getter;
}
if (setter) {
descriptor.set = setter;
}
// If it was accessor property we're done and return here
// in order to avoid adding `value` to the descriptor.
return descriptor;
}
}
// If we got this far we know that object has an own property that is
// not an accessor so we set it as a value and return descriptor.
descriptor.value = object[property];
return descriptor;
};
}
// ES5 15.2.3.4
// http://es5.github.com/#x15.2.3.4
if (!Object.getOwnPropertyNames) {
Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
return Object.keys(object);
};
}
// ES5 15.2.3.5
// http://es5.github.com/#x15.2.3.5
if (!Object.create) {
Object.create = function create(prototype, properties) {
var object;
function Type() {} // An empty constructor.
if (prototype === null) {
object = { "__proto__": null };
} else {
if (typeof prototype !== "object" && typeof prototype !== "function") {
// In the native implementation `parent` can be `null`
// OR *any* `instanceof Object` (Object|Function|Array|RegExp|etc)
// Use `typeof` tho, b/c in old IE, DOM elements are not `instanceof Object`
// like they are in modern browsers. Using `Object.create` on DOM elements
// is...err...probably inappropriate, but the native version allows for it.
throw new TypeError("Object prototype may only be an Object or null"); // same msg as Chrome
}
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
object.__proto__ = prototype;
}
if (properties !== void 0) {
Object.defineProperties(object, properties);
}
return object;
};
}
// ES5 15.2.3.6
// http://es5.github.com/#x15.2.3.6
// Patch for WebKit and IE8 standard mode
// Designed by hax <hax.github.com>
// related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
// IE8 Reference:
// http://msdn.microsoft.com/en-us/library/dd282900.aspx
// http://msdn.microsoft.com/en-us/library/dd229916.aspx
// WebKit Bugs:
// https://bugs.webkit.org/show_bug.cgi?id=36423
function doesDefinePropertyWork(object) {
try {
Object.defineProperty(object, "sentinel", {});
return "sentinel" in object;
} catch (exception) {
// returns falsy
}
}
// check whether defineProperty works if it's given. Otherwise,
// shim partially.
if (Object.defineProperty) {
var definePropertyWorksOnObject = doesDefinePropertyWork({});
var definePropertyWorksOnDom = typeof document == "undefined" ||
doesDefinePropertyWork(document.createElement("div"));
if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
var definePropertyFallback = Object.defineProperty;
}
}
if (!Object.defineProperty || definePropertyFallback) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if ((typeof object != "object" && typeof object != "function") || object === null) {
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
}
if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) {
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
}
// make a valiant attempt to use the real defineProperty
// for I8's DOM elements.
if (definePropertyFallback) {
try {
return definePropertyFallback.call(Object, object, property, descriptor);
} catch (exception) {
// try the shim if the real one doesn't work
}
}
// If it's a data property.
if (owns(descriptor, "value")) {
// fail silently if "writable", "enumerable", or "configurable"
// are requested but not supported
/*
// alternate approach:
if ( // can't implement these features; allow false but not true
!(owns(descriptor, "writable") ? descriptor.writable : true) ||
!(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(owns(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
*/
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don't hit an inherited
// accessor.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.__proto__ = prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors) {
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
}
// If we got that far then getters and setters can be defined !!
if (owns(descriptor, "get")) {
defineGetter(object, property, descriptor.get);
}
if (owns(descriptor, "set")) {
defineSetter(object, property, descriptor.set);
}
}
return object;
};
}
// ES5 15.2.3.7
// http://es5.github.com/#x15.2.3.7
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property) && property != "__proto__") {
Object.defineProperty(object, property, properties[property]);
}
}
return object;
};
}
// ES5 15.2.3.8
// http://es5.github.com/#x15.2.3.8
if (!Object.seal) {
Object.seal = function seal(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.9
// http://es5.github.com/#x15.2.3.9
if (!Object.freeze) {
Object.freeze = function freeze(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// detect a Rhino bug and patch it
try {
Object.freeze(function () {});
} catch (exception) {
Object.freeze = (function freeze(freezeObject) {
return function freeze(object) {
if (typeof object == "function") {
return object;
} else {
return freezeObject(object);
}
};
})(Object.freeze);
}
// ES5 15.2.3.10
// http://es5.github.com/#x15.2.3.10
if (!Object.preventExtensions) {
Object.preventExtensions = function preventExtensions(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.11
// http://es5.github.com/#x15.2.3.11
if (!Object.isSealed) {
Object.isSealed = function isSealed(object) {
return false;
};
}
// ES5 15.2.3.12
// http://es5.github.com/#x15.2.3.12
if (!Object.isFrozen) {
Object.isFrozen = function isFrozen(object) {
return false;
};
}
// ES5 15.2.3.13
// http://es5.github.com/#x15.2.3.13
if (!Object.isExtensible) {
Object.isExtensible = function isExtensible(object) {
// 1. If Type(O) is not Object throw a TypeError exception.
if (Object(object) !== object) {
throw new TypeError(); // TODO message
}
// 2. Return the Boolean value of the [[Extensible]] internal property of O.
var name = '';
while (owns(object, name)) {
name += '?';
}
object[name] = true;
var returnValue = owns(object, name);
delete object[name];
return returnValue;
};
}
});

6
js/lib/es5-shim-2.0.2/es5-sham.min.js vendored Executable file
View File

@ -0,0 +1,6 @@
(function(d){"function"==typeof define?define(d):"function"==typeof YUI?YUI.add("es5-sham",d):d()})(function(){function d(a){try{return Object.defineProperty(a,"sentinel",{}),"sentinel"in a}catch(b){}}Object.getPrototypeOf||(Object.getPrototypeOf=function(a){return a.__proto__||(a.constructor?a.constructor.prototype:prototypeOfObject)});Object.getOwnPropertyDescriptor||(Object.getOwnPropertyDescriptor=function(a,b){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError("Object.getOwnPropertyDescriptor called on a non-object: "+
a);if(owns(a,b)){var c={enumerable:true,configurable:true};if(supportsAccessors){var g=a.__proto__;a.__proto__=prototypeOfObject;var d=lookupGetter(a,b),e=lookupSetter(a,b);a.__proto__=g;if(d||e){if(d)c.get=d;if(e)c.set=e;return c}}c.value=a[b];return c}});Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(a){return Object.keys(a)});Object.create||(Object.create=function(a,b){function c(){}var d;if(a===null)d={__proto__:null};else{if(typeof a!=="object"&&typeof a!=="function")throw new TypeError("Object prototype may only be an Object or null");
c.prototype=a;d=new c;d.__proto__=a}b!==void 0&&Object.defineProperties(d,b);return d});if(Object.defineProperty){var f=d({}),h="undefined"==typeof document||d(document.createElement("div"));if(!f||!h)var e=Object.defineProperty}if(!Object.defineProperty||e)Object.defineProperty=function(a,b,c){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError("Object.defineProperty called on non-object: "+a);if(typeof c!="object"&&typeof c!="function"||c===null)throw new TypeError("Property description must be an object: "+
c);if(e)try{return e.call(Object,a,b,c)}catch(d){}if(owns(c,"value"))if(supportsAccessors&&(lookupGetter(a,b)||lookupSetter(a,b))){var f=a.__proto__;a.__proto__=prototypeOfObject;delete a[b];a[b]=c.value;a.__proto__=f}else a[b]=c.value;else{if(!supportsAccessors)throw new TypeError("getters & setters can not be defined on this javascript engine");owns(c,"get")&&defineGetter(a,b,c.get);owns(c,"set")&&defineSetter(a,b,c.set)}return a};Object.defineProperties||(Object.defineProperties=function(a,b){for(var c in b)owns(b,
c)&&c!="__proto__"&&Object.defineProperty(a,c,b[c]);return a});Object.seal||(Object.seal=function(a){return a});Object.freeze||(Object.freeze=function(a){return a});try{Object.freeze(function(){})}catch(j){var i=Object.freeze;Object.freeze=function(a){return typeof a=="function"?a:i(a)}}Object.preventExtensions||(Object.preventExtensions=function(a){return a});Object.isSealed||(Object.isSealed=function(){return false});Object.isFrozen||(Object.isFrozen=function(){return false});Object.isExtensible||
(Object.isExtensible=function(a){if(Object(a)!==a)throw new TypeError;for(var b="";owns(a,b);)b=b+"?";a[b]=true;var c=owns(a,b);delete a[b];return c})});

963
js/lib/es5-shim-2.0.2/es5-shim.js Executable file
View File

@ -0,0 +1,963 @@
// Copyright 2009-2012 by contributors, MIT License
// vim: ts=4 sts=4 sw=4 expandtab
// Module systems magic dance
(function (definition) {
// RequireJS
if (typeof define == "function") {
define(definition);
// YUI3
} else if (typeof YUI == "function") {
YUI.add("es5", definition);
// CommonJS and <script>
} else {
definition();
}
})(function () {
/**
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* Annotated ES5: http://es5.github.com/ (specific links below)
* ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
* Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/
*/
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://es5.github.com/#x15.3.4.5
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
if (typeof target != "function") {
throw new TypeError("Function.prototype.bind called on incompatible " + target);
}
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = slice.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 11. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 12. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 13. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 14. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
var bound = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs, the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Construct]] internal
// method of target providing args as the arguments.
var result = target.apply(
this,
args.concat(slice.call(arguments))
);
if (Object(result) === result) {
return result;
}
return this;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs, the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Call]] internal method
// of target providing boundThis as the this value and
// providing args as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
if(target.prototype) {
bound.prototype = Object.create(target.prototype);
}
// XXX bound.length is never writable, so don't even try
//
// 15. If the [[Class]] internal property of Target is "Function", then
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is
// larger.
// 16. Else set the length own property of F to 0.
// 17. Set the attributes of the length own property of F to the values
// specified in 15.3.5.1.
// TODO
// 18. Set the [[Extensible]] internal property of F to true.
// TODO
// 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
// 20. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
// thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
// false.
// 21. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
// [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
// and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property or the [[Code]], [[FormalParameters]], and
// [[Scope]] internal properties.
// XXX can't delete prototype in pure-js.
// 22. Return F.
return bound;
};
}
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally.
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var slice = prototypeOfArray.slice;
// Having a toString local variable name breaks in Opera so use _toString.
var _toString = call.bind(prototypeOfObject.toString);
var owns = call.bind(prototypeOfObject.hasOwnProperty);
// If JS engine supports accessors creating shortcuts.
var defineGetter;
var defineSetter;
var lookupGetter;
var lookupSetter;
var supportsAccessors;
if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
//
// Array
// =====
//
// ES5 15.4.4.12
// http://es5.github.com/#x15.4.4.12
// Default value for second param
// [bugfix, ielt9, old browsers]
// IE < 9 bug: [1,2].splice(0).join("") == "" but should be "12"
if ([1,2].splice(0).length != 2) {
var array_splice = Array.prototype.splice;
Array.prototype.splice = function(start, deleteCount) {
if (!arguments.length) {
return [];
} else {
return array_splice.apply(this, [
start === void 0 ? 0 : start,
deleteCount === void 0 ? (this.length - start) : deleteCount
].concat(slice.call(arguments, 2)))
}
};
}
// ES5 15.4.3.2
// http://es5.github.com/#x15.4.3.2
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return _toString(obj) == "[object Array]";
};
}
// The IsCallable() check in the Array functions
// has been replaced with a strict check on the
// internal class of the object to trap cases where
// the provided function was actually a regular
// expression literal, which in V8 and
// JavaScriptCore is a typeof "function". Only in
// V8 are regular expression literals permitted as
// reduce parameters, so it is desirable in the
// general case for the shim to match the more
// strict and common behavior of rejecting regular
// expressions.
// ES5 15.4.4.18
// http://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
// Check failure of by-index access of string characters (IE < 9)
// and failure of `0 in boxedString` (Rhino)
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
thisp = arguments[1],
i = -1,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
while (++i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object
// context
fun.call(thisp, self[i], i, object);
}
}
};
}
// ES5 15.4.4.19
// http://es5.github.com/#x15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, object);
}
return result;
};
}
// ES5 15.4.4.20
// http://es5.github.com/#x15.4.4.20
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
result = [],
value,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
value = self[i];
if (fun.call(thisp, value, i, object)) {
result.push(value);
}
}
}
return result;
};
}
// ES5 15.4.4.16
// http://es5.github.com/#x15.4.4.16
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
// ES5 15.4.4.17
// http://es5.github.com/#x15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
if (!Array.prototype.some) {
Array.prototype.some = function some(fun /*, thisp */) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, object)) {
return true;
}
}
return false;
};
}
// ES5 15.4.4.21
// http://es5.github.com/#x15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
// no value to return if no initial value and an empty array
if (!length && arguments.length == 1) {
throw new TypeError("reduce of empty array with no initial value");
}
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length) {
throw new TypeError("reduce of empty array with no initial value");
}
} while (true);
}
for (; i < length; i++) {
if (i in self) {
result = fun.call(void 0, result, self[i], i, object);
}
}
return result;
};
}
// ES5 15.4.4.22
// http://es5.github.com/#x15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var object = toObject(this),
self = splitString && _toString(this) == "[object String]" ?
this.split("") :
object,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (_toString(fun) != "[object Function]") {
throw new TypeError(fun + " is not a function");
}
// no value to return if no initial value, empty array
if (!length && arguments.length == 1) {
throw new TypeError("reduceRight of empty array with no initial value");
}
var result, i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0) {
throw new TypeError("reduceRight of empty array with no initial value");
}
} while (true);
}
do {
if (i in this) {
result = fun.call(void 0, result, self[i], i, object);
}
} while (i--);
return result;
};
}
// ES5 15.4.4.14
// http://es5.github.com/#x15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
var self = splitString && _toString(this) == "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = 0;
if (arguments.length > 1) {
i = toInteger(arguments[1]);
}
// handle negative indices
i = i >= 0 ? i : Math.max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
};
}
// ES5 15.4.4.15
// http://es5.github.com/#x15.4.4.15
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
var self = splitString && _toString(this) == "[object String]" ?
this.split("") :
toObject(this),
length = self.length >>> 0;
if (!length) {
return -1;
}
var i = length - 1;
if (arguments.length > 1) {
i = Math.min(i, toInteger(arguments[1]));
}
// handle negative indices
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && sought === self[i]) {
return i;
}
}
return -1;
};
}
//
// Object
// ======
//
// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
if (!Object.keys) {
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = true,
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null}) {
hasDontEnumBug = false;
}
Object.keys = function keys(object) {
if (
(typeof object != "object" && typeof object != "function") ||
object === null
) {
throw new TypeError("Object.keys called on a non-object");
}
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
//
// Date
// ====
//
// ES5 15.9.5.43
// http://es5.github.com/#x15.9.5.43
// This function returns a String value represent the instance in time
// represented by this Date object. The format of the String is the Date Time
// string format defined in 15.9.1.15. All fields are present in the String.
// The time zone is always UTC, denoted by the suffix Z. If the time value of
// this object is not a finite Number a RangeError exception is thrown.
var negativeDate = -62198755200000,
negativeYearString = "-000001";
if (
!Date.prototype.toISOString ||
(new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1)
) {
Date.prototype.toISOString = function toISOString() {
var result, length, value, year, month;
if (!isFinite(this)) {
throw new RangeError("Date.prototype.toISOString called on non-finite value.");
}
year = this.getUTCFullYear();
month = this.getUTCMonth();
// see https://github.com/kriskowal/es5-shim/issues/111
year += Math.floor(month / 12);
month = (month % 12 + 12) % 12;
// the date time string format is specified in 15.9.1.15.
result = [month + 1, this.getUTCDate(),
this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()];
year = (
(year < 0 ? "-" : (year > 9999 ? "+" : "")) +
("00000" + Math.abs(year))
.slice(0 <= year && year <= 9999 ? -4 : -6)
);
length = result.length;
while (length--) {
value = result[length];
// pad months, days, hours, minutes, and seconds to have two
// digits.
if (value < 10) {
result[length] = "0" + value;
}
}
// pad milliseconds to have three digits.
return (
year + "-" + result.slice(0, 2).join("-") +
"T" + result.slice(2).join(":") + "." +
("000" + this.getUTCMilliseconds()).slice(-3) + "Z"
);
};
}
// ES5 15.9.5.44
// http://es5.github.com/#x15.9.5.44
// This function provides a String representation of a Date object for use by
// JSON.stringify (15.12.3).
var dateToJSONIsSupported = false;
try {
dateToJSONIsSupported = (
Date.prototype.toJSON &&
new Date(NaN).toJSON() === null &&
new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 &&
Date.prototype.toJSON.call({ // generic
toISOString: function () {
return true;
}
})
);
} catch (e) {
}
if (!dateToJSONIsSupported) {
Date.prototype.toJSON = function toJSON(key) {
// When the toJSON method is called with argument key, the following
// steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be toPrimitive(O, hint Number).
var o = Object(this),
tv = toPrimitive(o),
toISO;
// 3. If tv is a Number and is not finite, return null.
if (typeof tv === "number" && !isFinite(tv)) {
return null;
}
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
toISO = o.toISOString;
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (typeof toISO != "function") {
throw new TypeError("toISOString property is not callable");
}
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return toISO.call(o);
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// ES5 15.9.4.2
// http://es5.github.com/#x15.9.4.2
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
if (!Date.parse || "Date.parse is buggy") {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
Date = (function(NativeDate) {
// Date.length === 7
var newDate = function Date(Y, M, D, h, m, s, ms) {
var length = arguments.length;
if (this instanceof NativeDate) {
var date = length == 1 && String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(newDate.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) :
length >= 6 ? new NativeDate(Y, M, D, h, m, s) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
// Prevent mixups with unfixed Date object
date.constructor = newDate;
return date;
}
return NativeDate.apply(this, arguments);
};
// 15.9.1.15 Date Time String Format.
var isoDateExpression = new RegExp("^" +
"(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign +
// 6-digit extended year
"(?:-(\\d{2})" + // optional month capture
"(?:-(\\d{2})" + // optional day capture
"(?:" + // capture hours:minutes:seconds.milliseconds
"T(\\d{2})" + // hours capture
":(\\d{2})" + // minutes capture
"(?:" + // optional :seconds.milliseconds
":(\\d{2})" + // seconds capture
"(?:\\.(\\d{3}))?" + // milliseconds capture
")?" +
"(" + // capture UTC offset component
"Z|" + // UTC capture
"(?:" + // offset specifier +/-hours:minutes
"([-+])" + // sign capture
"(\\d{2})" + // hours offset capture
":(\\d{2})" + // minutes offset capture
")" +
")?)?)?)?" +
"$");
var months = [
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
];
function dayFromMonth(year, month) {
var t = month > 1 ? 1 : 0;
return (
months[month] +
Math.floor((year - 1969 + t) / 4) -
Math.floor((year - 1901 + t) / 100) +
Math.floor((year - 1601 + t) / 400) +
365 * (year - 1970)
);
}
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate) {
newDate[key] = NativeDate[key];
}
// Copy "native" methods explicitly; they may be non-enumerable
newDate.now = NativeDate.now;
newDate.UTC = NativeDate.UTC;
newDate.prototype = NativeDate.prototype;
newDate.prototype.constructor = Date;
// Upgrade Date.parse to handle simplified ISO 8601 strings
newDate.parse = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
// parse months, days, hours, minutes, seconds, and milliseconds
// provide default values if necessary
// parse the UTC offset component
var year = Number(match[1]),
month = Number(match[2] || 1) - 1,
day = Number(match[3] || 1) - 1,
hour = Number(match[4] || 0),
minute = Number(match[5] || 0),
second = Number(match[6] || 0),
millisecond = Number(match[7] || 0),
// When time zone is missed, local offset should be used
// (ES 5.1 bug)
// see https://bugs.ecmascript.org/show_bug.cgi?id=112
offset = !match[4] || match[8] ?
0 : Number(new Date(1970, 0)),
signOffset = match[9] === "-" ? 1 : -1,
hourOffset = Number(match[10] || 0),
minuteOffset = Number(match[11] || 0),
result;
if (
hour < (
minute > 0 || second > 0 || millisecond > 0 ?
24 : 25
) &&
minute < 60 && second < 60 && millisecond < 1000 &&
month > -1 && month < 12 && hourOffset < 24 &&
minuteOffset < 60 && // detect invalid offsets
day > -1 &&
day < (
dayFromMonth(year, month + 1) -
dayFromMonth(year, month)
)
) {
result = (
(dayFromMonth(year, month) + day) * 24 +
hour +
hourOffset * signOffset
) * 60;
result = (
(result + minute + minuteOffset * signOffset) * 60 +
second
) * 1000 + millisecond + offset;
if (-8.64e15 <= result && result <= 8.64e15) {
return result;
}
}
return NaN;
}
return NativeDate.parse.apply(this, arguments);
};
return newDate;
})(Date);
}
// ES5 15.9.4.4
// http://es5.github.com/#x15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
//
// String
// ======
//
// ES5 15.5.4.14
// http://es5.github.com/#x15.5.4.14
// [bugfix, chrome]
// If separator is undefined, then the result array contains just one String,
// which is the this value (converted to a String). If limit is not undefined,
// then the output array is truncated so that it contains no more than limit
// elements.
// "0".split(undefined, 0) -> []
if("0".split(void 0, 0).length) {
var string_split = String.prototype.split;
String.prototype.split = function(separator, limit) {
if(separator === void 0 && limit === 0)return [];
return string_split.apply(this, arguments);
}
}
// ECMA-262, 3rd B.2.3
// Note an ECMAScript standart, although ECMAScript 3rd Edition has a
// non-normative section suggesting uniform semantics and it should be
// normalized across all browsers
// [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE
if("".substr && "0b".substr(-1) !== "b") {
var string_substr = String.prototype.substr;
/**
* Get the substring of a string
* @param {integer} start where to start the substring
* @param {integer} length how many characters to return
* @return {string}
*/
String.prototype.substr = function(start, length) {
return string_substr.call(
this,
start < 0 ? (start = this.length + start) < 0 ? 0 : start : start,
length
);
}
}
// ES5 15.5.4.20
// http://es5.github.com/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
if (this === undefined || this === null) {
throw new TypeError("can't convert "+this+" to object");
}
return String(this)
.replace(trimBeginRegexp, "")
.replace(trimEndRegexp, "");
};
}
//
// Util
// ======
//
// ES5 9.4
// http://es5.github.com/#x9.4
// http://jsperf.com/to-integer
function toInteger(n) {
n = +n;
if (n !== n) { // isNaN
n = 0;
} else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
return n;
}
function isPrimitive(input) {
var type = typeof input;
return (
input === null ||
type === "undefined" ||
type === "boolean" ||
type === "number" ||
type === "string"
);
}
function toPrimitive(input) {
var val, valueOf, toString;
if (isPrimitive(input)) {
return input;
}
valueOf = input.valueOf;
if (typeof valueOf === "function") {
val = valueOf.call(input);
if (isPrimitive(val)) {
return val;
}
}
toString = input.toString;
if (typeof toString === "function") {
val = toString.call(input);
if (isPrimitive(val)) {
return val;
}
}
throw new TypeError();
}
// ES5 9.9
// http://es5.github.com/#x9.9
var toObject = function (o) {
if (o == null) { // this matches both null and undefined
throw new TypeError("can't convert "+o+" to object");
}
return Object(o);
};
});

16
js/lib/es5-shim-2.0.2/es5-shim.min.js vendored Executable file
View File

@ -0,0 +1,16 @@
(function(p){"function"==typeof define?define(p):"function"==typeof YUI?YUI.add("es5",p):p()})(function(){function p(a){a=+a;a!==a?a=0:0!==a&&(a!==1/0&&a!==-(1/0))&&(a=(0<a||-1)*Math.floor(Math.abs(a)));return a}function s(a){var b=typeof a;return null===a||"undefined"===b||"boolean"===b||"number"===b||"string"===b}Function.prototype.bind||(Function.prototype.bind=function(a){var b=this;if("function"!=typeof b)throw new TypeError("Function.prototype.bind called on incompatible "+b);var d=q.call(arguments,
1),c=function(){if(this instanceof c){var e=b.apply(this,d.concat(q.call(arguments)));return Object(e)===e?e:this}return b.apply(a,d.concat(q.call(arguments)))};b.prototype&&(c.prototype=Object.create(b.prototype));return c});var m=Function.prototype.call,o=Object.prototype,q=Array.prototype.slice,h=m.bind(o.toString),t=m.bind(o.hasOwnProperty);t(o,"__defineGetter__")&&(m.bind(o.__defineGetter__),m.bind(o.__defineSetter__),m.bind(o.__lookupGetter__),m.bind(o.__lookupSetter__));if(2!=[1,2].splice(0).length){var x=
Array.prototype.splice;Array.prototype.splice=function(a,b){return arguments.length?x.apply(this,[a===void 0?0:a,b===void 0?this.length-a:b].concat(q.call(arguments,2))):[]}}Array.isArray||(Array.isArray=function(a){return h(a)=="[object Array]"});var m=Object("a"),k="a"!=m[0]||!(0 in m);Array.prototype.forEach||(Array.prototype.forEach=function(a,b){var d=l(this),c=k&&h(this)=="[object String]"?this.split(""):d,e=-1,f=c.length>>>0;if(h(a)!="[object Function]")throw new TypeError;for(;++e<f;)e in
c&&a.call(b,c[e],e,d)});Array.prototype.map||(Array.prototype.map=function(a,b){var d=l(this),c=k&&h(this)=="[object String]"?this.split(""):d,e=c.length>>>0,f=Array(e);if(h(a)!="[object Function]")throw new TypeError(a+" is not a function");for(var g=0;g<e;g++)g in c&&(f[g]=a.call(b,c[g],g,d));return f});Array.prototype.filter||(Array.prototype.filter=function(a,b){var d=l(this),c=k&&h(this)=="[object String]"?this.split(""):d,e=c.length>>>0,f=[],g;if(h(a)!="[object Function]")throw new TypeError(a+
" is not a function");for(var i=0;i<e;i++)if(i in c){g=c[i];a.call(b,g,i,d)&&f.push(g)}return f});Array.prototype.every||(Array.prototype.every=function(a,b){var d=l(this),c=k&&h(this)=="[object String]"?this.split(""):d,e=c.length>>>0;if(h(a)!="[object Function]")throw new TypeError(a+" is not a function");for(var f=0;f<e;f++)if(f in c&&!a.call(b,c[f],f,d))return false;return true});Array.prototype.some||(Array.prototype.some=function(a,b){var d=l(this),c=k&&h(this)=="[object String]"?this.split(""):
d,e=c.length>>>0;if(h(a)!="[object Function]")throw new TypeError(a+" is not a function");for(var f=0;f<e;f++)if(f in c&&a.call(b,c[f],f,d))return true;return false});Array.prototype.reduce||(Array.prototype.reduce=function(a){var b=l(this),d=k&&h(this)=="[object String]"?this.split(""):b,c=d.length>>>0;if(h(a)!="[object Function]")throw new TypeError(a+" is not a function");if(!c&&arguments.length==1)throw new TypeError("reduce of empty array with no initial value");var e=0,f;if(arguments.length>=
2)f=arguments[1];else{do{if(e in d){f=d[e++];break}if(++e>=c)throw new TypeError("reduce of empty array with no initial value");}while(1)}for(;e<c;e++)e in d&&(f=a.call(void 0,f,d[e],e,b));return f});Array.prototype.reduceRight||(Array.prototype.reduceRight=function(a){var b=l(this),d=k&&h(this)=="[object String]"?this.split(""):b,c=d.length>>>0;if(h(a)!="[object Function]")throw new TypeError(a+" is not a function");if(!c&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");
var e,c=c-1;if(arguments.length>=2)e=arguments[1];else{do{if(c in d){e=d[c--];break}if(--c<0)throw new TypeError("reduceRight of empty array with no initial value");}while(1)}do c in this&&(e=a.call(void 0,e,d[c],c,b));while(c--);return e});if(!Array.prototype.indexOf||-1!=[0,1].indexOf(1,2))Array.prototype.indexOf=function(a){var b=k&&h(this)=="[object String]"?this.split(""):l(this),d=b.length>>>0;if(!d)return-1;var c=0;arguments.length>1&&(c=p(arguments[1]));for(c=c>=0?c:Math.max(0,d+c);c<d;c++)if(c in
b&&b[c]===a)return c;return-1};if(!Array.prototype.lastIndexOf||-1!=[0,1].lastIndexOf(0,-3))Array.prototype.lastIndexOf=function(a){var b=k&&h(this)=="[object String]"?this.split(""):l(this),d=b.length>>>0;if(!d)return-1;var c=d-1;arguments.length>1&&(c=Math.min(c,p(arguments[1])));for(c=c>=0?c:d-Math.abs(c);c>=0;c--)if(c in b&&a===b[c])return c;return-1};if(!Object.keys){var v=!0,w="toString toLocaleString valueOf hasOwnProperty isPrototypeOf propertyIsEnumerable constructor".split(" "),y=w.length,
r;for(r in{toString:null})v=!1;Object.keys=function(a){if(typeof a!="object"&&typeof a!="function"||a===null)throw new TypeError("Object.keys called on a non-object");var b=[],d;for(d in a)t(a,d)&&b.push(d);if(v)for(d=0;d<y;d++){var c=w[d];t(a,c)&&b.push(c)}return b}}if(!Date.prototype.toISOString||-1===(new Date(-621987552E5)).toISOString().indexOf("-000001"))Date.prototype.toISOString=function(){var a,b,d,c;if(!isFinite(this))throw new RangeError("Date.prototype.toISOString called on non-finite value.");
c=this.getUTCFullYear();a=this.getUTCMonth();c=c+Math.floor(a/12);a=[(a%12+12)%12+1,this.getUTCDate(),this.getUTCHours(),this.getUTCMinutes(),this.getUTCSeconds()];c=(c<0?"-":c>9999?"+":"")+("00000"+Math.abs(c)).slice(0<=c&&c<=9999?-4:-6);for(b=a.length;b--;){d=a[b];d<10&&(a[b]="0"+d)}return c+"-"+a.slice(0,2).join("-")+"T"+a.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"};r=!1;try{r=Date.prototype.toJSON&&null===(new Date(NaN)).toJSON()&&-1!==(new Date(-621987552E5)).toJSON().indexOf("-000001")&&
Date.prototype.toJSON.call({toISOString:function(){return true}})}catch(F){}r||(Date.prototype.toJSON=function(){var a=Object(this),b;a:if(s(a))b=a;else{b=a.valueOf;if(typeof b==="function"){b=b.call(a);if(s(b))break a}b=a.toString;if(typeof b==="function"){b=b.call(a);if(s(b))break a}throw new TypeError;}if(typeof b==="number"&&!isFinite(b))return null;b=a.toISOString;if(typeof b!="function")throw new TypeError("toISOString property is not callable");return b.call(a)});var g=Date,u=function(a,b){var d=
b>1?1:0;return z[b]+Math.floor((a-1969+d)/4)-Math.floor((a-1901+d)/100)+Math.floor((a-1601+d)/400)+365*(a-1970)},n=function(a,b,d,c,e,f,h){var i=arguments.length;if(this instanceof g){i=i==1&&String(a)===a?new g(n.parse(a)):i>=7?new g(a,b,d,c,e,f,h):i>=6?new g(a,b,d,c,e,f):i>=5?new g(a,b,d,c,e):i>=4?new g(a,b,d,c):i>=3?new g(a,b,d):i>=2?new g(a,b):i>=1?new g(a):new g;i.constructor=n;return i}return g.apply(this,arguments)},A=RegExp("^(\\d{4}|[+-]\\d{6})(?:-(\\d{2})(?:-(\\d{2})(?:T(\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d{3}))?)?(Z|(?:([-+])(\\d{2}):(\\d{2})))?)?)?)?$"),
z=[0,31,59,90,120,151,181,212,243,273,304,334,365],j;for(j in g)n[j]=g[j];n.now=g.now;n.UTC=g.UTC;n.prototype=g.prototype;n.prototype.constructor=Date;n.parse=function(a){var b=A.exec(a);if(b){var d=Number(b[1]),c=Number(b[2]||1)-1,e=Number(b[3]||1)-1,f=Number(b[4]||0),h=Number(b[5]||0),i=Number(b[6]||0),j=Number(b[7]||0),m=!b[4]||b[8]?0:Number(new Date(1970,0)),k=b[9]==="-"?1:-1,l=Number(b[10]||0),b=Number(b[11]||0);if(f<(h>0||i>0||j>0?24:25)&&h<60&&i<60&&j<1E3&&c>-1&&c<12&&l<24&&b<60&&e>-1&&e<u(d,
c+1)-u(d,c)){d=((u(d,c)+e)*24+f+l*k)*60;d=((d+h+b*k)*60+i)*1E3+j+m;if(-864E13<=d&&d<=864E13)return d}return NaN}return g.parse.apply(this,arguments)};Date=n;Date.now||(Date.now=function(){return(new Date).getTime()});if("0".split(void 0,0).length){var B=String.prototype.split;String.prototype.split=function(a,b){return a===void 0&&b===0?[]:B.apply(this,arguments)}}if("".substr&&"b"!=="0b".substr(-1)){var C=String.prototype.substr;String.prototype.substr=function(a,b){return C.call(this,a<0?(a=this.length+
a)<0?0:a:a,b)}}j="\t\n\x0B\f\r \u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff";if(!String.prototype.trim||j.trim()){j="["+j+"]";var D=RegExp("^"+j+j+"*"),E=RegExp(j+j+"*$");String.prototype.trim=function(){if(this===void 0||this===null)throw new TypeError("can't convert "+this+" to object");return String(this).replace(D,"").replace(E,"")}}var l=function(a){if(a==null)throw new TypeError("can't convert "+a+" to object");return Object(a)}});

2
js/lib/es5-shim-2.0.2/minify Executable file
View File

@ -0,0 +1,2 @@
closure < es5-shim.js > es5-shim.min.js
closure < es5-sham.js > es5-sham.min.js

View File

@ -0,0 +1,31 @@
{
"name": "es5-shim",
"version": "2.0.2",
"description": "ES5 as implementable on previous engines",
"homepage": "http://github.com/kriskowal/es5-shim/",
"contributors": [
"Kris Kowal <kris@cixar.com> (http://github.com/kriskowal/)",
"Sami Samhuri <sami.samhuri@gmail.com> (http://samhuri.net/)",
"Florian Schäfer <florian.schaefer@gmail.com> (http://github.com/fschaefer)",
"Irakli Gozalishvili <rfobic@gmail.com> (http://jeditoolkit.com)",
"Kit Cambridge <kitcambridge@gmail.com> (http://kitcambridge.github.com)"
],
"bugs": {
"mail": "kris@cixar.com",
"url": "http://github.com/kriskowal/es5-shim/issues"
},
"licenses": [
{
"type": "MIT",
"url": "http://github.com/kriskowal/es5-shim/raw/master/LICENSE"
}
],
"main": "es5-shim.js",
"repository": {
"type": "git",
"url": "http://github.com/kriskowal/es5-shim.git"
},
"engines": {
"node": ">=0.2.0"
}
}

View File

@ -0,0 +1,59 @@
// This methods allows the killing of built-in functions,
// so the shim can take over with that implementation
var HLP = (function() {
"use strict";
var kill;
kill = function(_class, methods) {
/*if(!Array.isArray(methods))
return;*/
if(!_class.originals)
_class.originals = {};
for (var i = 0, len = methods.length; i < len; i++) {
var obj = methods[i];
_class.originals[obj] = _class[obj];
delete _class[obj];
if (obj in _class) {
// try something more aggressive since V8 at least
// appears to ignore the delete.
_class[obj] = null;
if (_class[obj]) {
console.log("Couln't overwrite", obj, "of", _class);
}
}
}
};
return { kill: kill };
}());
HLP.kill(Function.prototype, [
'bind'
]);
HLP.kill(Array, [
'isArray'
]);
HLP.kill(String.prototype, [
"trim"
]);
HLP.kill(Object, [
'keys'
]);
HLP.kill(Date, [
'now', 'parse'
]);
HLP.kill(Date.prototype, [
"toJSON", "toISOString"
]);
HLP.kill(Array.prototype, [
'forEach', 'some', 'every',
'indexOf', 'lastIndexOf',
'map', 'filter',
'reduce', 'reduceRight'
]);

View File

@ -0,0 +1,34 @@
beforeEach(function() {
this.addMatchers({
toExactlyMatch: function(expected) {
var a1, a2,
l, i,
key,
actual = this.actual;
var getKeys = function(o) {
var a = [];
for(key in o) {
if(o.hasOwnProperty(key)) {
a.push(key);
}
}
return a;
}
a1 = getKeys(actual);
a2 = getKeys(expected);
l = a1.length;
if(l !== a2.length) {
return false;
}
for(i = 0; i < l; i++) {
key = a1[i];
expect(key).toEqual(a2[i]);
expect(actual[key]).toEqual(expected[key]);
}
return true;
}
})
});

View File

@ -0,0 +1,3 @@
function implement() {
throw 'Not implemented';
}

View File

@ -0,0 +1,62 @@
<!DOCTYPE HTML>
<html>
<head>
<title>Jasmine Spec Runner</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine.css">
<script type="text/javascript" src="lib/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-html.js"></script>
<script type="text/javascript" src="lib/json2.js"></script>
<!-- include helper files here... -->
<script src="helpers/h.js"></script>
<script src="helpers/h-kill.js"></script>
<script src="helpers/h-matchers.js"></script>
<!-- include source files here... -->
<script src="../es5-shim.js"></script>
<!-- include spec files here... -->
<script src="spec/s-array.js"></script>
<script src="spec/s-function.js"></script>
<script src="spec/s-string.js"></script>
<script src="spec/s-object.js"></script>
<script src="spec/s-date.js"></script>
<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var trivialReporter = new jasmine.TrivialReporter();
jasmineEnv.addReporter(trivialReporter);
jasmineEnv.specFilter = function(spec) {
return trivialReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body>
</body>
</html>

View File

@ -0,0 +1,190 @@
jasmine.TrivialReporter = function(doc) {
this.document = doc || document;
this.suiteDivs = {};
this.logRunningSpecs = false;
};
jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) {
var el = document.createElement(type);
for (var i = 2; i < arguments.length; i++) {
var child = arguments[i];
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
} else {
if (child) { el.appendChild(child); }
}
}
for (var attr in attrs) {
if (attr == "className") {
el[attr] = attrs[attr];
} else {
el.setAttribute(attr, attrs[attr]);
}
}
return el;
};
jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) {
var showPassed, showSkipped;
this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' },
this.createDom('div', { className: 'banner' },
this.createDom('div', { className: 'logo' },
this.createDom('span', { className: 'title' }, "Jasmine"),
this.createDom('span', { className: 'version' }, runner.env.versionString())),
this.createDom('div', { className: 'options' },
"Show ",
showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "),
showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }),
this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped")
)
),
this.runnerDiv = this.createDom('div', { className: 'runner running' },
this.createDom('a', { className: 'run_spec', href: '?' }, "run all"),
this.runnerMessageSpan = this.createDom('span', {}, "Running..."),
this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, ""))
);
this.document.body.appendChild(this.outerDiv);
var suites = runner.suites();
for (var i = 0; i < suites.length; i++) {
var suite = suites[i];
var suiteDiv = this.createDom('div', { className: 'suite' },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"),
this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description));
this.suiteDivs[suite.id] = suiteDiv;
var parentDiv = this.outerDiv;
if (suite.parentSuite) {
parentDiv = this.suiteDivs[suite.parentSuite.id];
}
parentDiv.appendChild(suiteDiv);
}
this.startedAt = new Date();
var self = this;
showPassed.onclick = function(evt) {
if (showPassed.checked) {
self.outerDiv.className += ' show-passed';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, '');
}
};
showSkipped.onclick = function(evt) {
if (showSkipped.checked) {
self.outerDiv.className += ' show-skipped';
} else {
self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, '');
}
};
};
jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) {
var results = runner.results();
var className = (results.failedCount > 0) ? "runner failed" : "runner passed";
this.runnerDiv.setAttribute("class", className);
//do it twice for IE
this.runnerDiv.setAttribute("className", className);
var specs = runner.specs();
var specCount = 0;
for (var i = 0; i < specs.length; i++) {
if (this.specFilter(specs[i])) {
specCount++;
}
}
var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s");
message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s";
this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild);
this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString()));
};
jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) {
var results = suite.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.totalCount === 0) { // todo: change this to check results.skipped
status = 'skipped';
}
this.suiteDivs[suite.id].className += " " + status;
};
jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) {
if (this.logRunningSpecs) {
this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...');
}
};
jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) {
var results = spec.results();
var status = results.passed() ? 'passed' : 'failed';
if (results.skipped) {
status = 'skipped';
}
var specDiv = this.createDom('div', { className: 'spec ' + status },
this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"),
this.createDom('a', {
className: 'description',
href: '?spec=' + encodeURIComponent(spec.getFullName()),
title: spec.getFullName()
}, spec.description));
var resultItems = results.getItems();
var messagesDiv = this.createDom('div', { className: 'messages' });
for (var i = 0; i < resultItems.length; i++) {
var result = resultItems[i];
if (result.type == 'log') {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString()));
} else if (result.type == 'expect' && result.passed && !result.passed()) {
messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message));
if (result.trace.stack) {
messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack));
}
}
}
if (messagesDiv.childNodes.length > 0) {
specDiv.appendChild(messagesDiv);
}
this.suiteDivs[spec.suite.id].appendChild(specDiv);
};
jasmine.TrivialReporter.prototype.log = function() {
var console = jasmine.getGlobal().console;
if (console && console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
console.log(arguments); // ie fix: console.log.apply doesn't exist on ie
}
}
};
jasmine.TrivialReporter.prototype.getLocation = function() {
return this.document.location;
};
jasmine.TrivialReporter.prototype.specFilter = function(spec) {
var paramMap = {};
var params = this.getLocation().search.substring(1).split('&');
for (var i = 0; i < params.length; i++) {
var p = params[i].split('=');
paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
}
if (!paramMap.spec) {
return true;
}
return spec.getFullName().indexOf(paramMap.spec) === 0;
};

View File

@ -0,0 +1,166 @@
body {
font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif;
}
.jasmine_reporter a:visited, .jasmine_reporter a {
color: #303;
}
.jasmine_reporter a:hover, .jasmine_reporter a:active {
color: blue;
}
.run_spec {
float:right;
padding-right: 5px;
font-size: .8em;
text-decoration: none;
}
.jasmine_reporter {
margin: 0 5px;
}
.banner {
color: #303;
background-color: #fef;
padding: 5px;
}
.logo {
float: left;
font-size: 1.1em;
padding-left: 5px;
}
.logo .version {
font-size: .6em;
padding-left: 1em;
}
.runner.running {
background-color: yellow;
}
.options {
text-align: right;
font-size: .8em;
}
.suite {
border: 1px outset gray;
margin: 5px 0;
padding-left: 1em;
}
.suite .suite {
margin: 5px;
}
.suite.passed {
background-color: #dfd;
}
.suite.failed {
background-color: #fdd;
}
.spec {
margin: 5px;
padding-left: 1em;
clear: both;
}
.spec.failed, .spec.passed, .spec.skipped {
padding-bottom: 5px;
border: 1px solid gray;
}
.spec.failed {
background-color: #fbb;
border-color: red;
}
.spec.passed {
background-color: #bfb;
border-color: green;
}
.spec.skipped {
background-color: #bbb;
}
.messages {
border-left: 1px dashed gray;
padding-left: 1em;
padding-right: 1em;
}
.passed {
background-color: #cfc;
display: none;
}
.failed {
background-color: #fbb;
}
.skipped {
color: #777;
background-color: #eee;
display: none;
}
/*.resultMessage {*/
/*white-space: pre;*/
/*}*/
.resultMessage span.result {
display: block;
line-height: 2em;
color: black;
}
.resultMessage .mismatch {
color: black;
}
.stackTrace {
white-space: pre;
font-size: .8em;
margin-left: 10px;
max-height: 5em;
overflow: auto;
border: 1px inset red;
padding: 1em;
background: #eef;
}
.finished-at {
padding-left: 1em;
font-size: .6em;
}
.show-passed .passed,
.show-skipped .skipped {
display: block;
}
#jasmine_content {
position:fixed;
right: 100%;
}
.runner {
border: 1px solid gray;
display: block;
margin: 5px 0;
padding: 2px 0 2px 10px;
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 905 B

View File

@ -0,0 +1,478 @@
/*
http://www.JSON.org/json2.js
2009-08-17
Public Domain.
NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
See http://www.JSON.org/js.html
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or '&nbsp;'),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
*/
/*jslint evil: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
"use strict";
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (!this.JSON) {
this.JSON = {};
}
(function () {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf()) ?
this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ?
'"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c :
'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' :
'"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0 ? '[]' :
gap ? '[\n' + gap +
partial.join(',\n' + gap) + '\n' +
mind + ']' :
'[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
k = rep[i];
if (typeof k === 'string') {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0 ? '{}' :
gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
mind + '}' : '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,117 @@
describe('Date', function () {
describe('now', function () {
it('should be the current time', function () {
expect(Date.now() === new Date().getTime()).toBe(true);
});
});
describe("parse", function () {
// TODO: Write the rest of the test.
it('should support extended years', function () {
expect(Date.parse('0001-01-01T00:00:00Z')).toBe(-62135596800000);
expect(Date.parse('+275760-09-13T00:00:00.000Z')).toBe(8.64e15);
expect(Date.parse('+033658-09-27T01:46:40.000Z')).toBe(1e15);
expect(Date.parse('-000001-01-01T00:00:00Z')).toBe(-62198755200000);
expect(Date.parse('+002009-12-15T00:00:00Z')).toBe(1260835200000);
});
it('should work', function () {
//Chrome 19 Opera 12 Firefox 11 IE 9 Safari 5.1.1
expect(Date.parse("2012-11-31T23:59:59.000Z")).toBeFalsy(); //1354406399000 NaN NaN 1354406399000 NaN
expect(Date.parse("2012-12-31T23:59:59.000Z")).toBe(1356998399000); //1356998399000 1356998399000 1356998399000 1356998399000 1356998399000
expect(Date.parse("2012-12-31T23:59:60.000Z")).toBeFalsy(); //NaN NaN NaN NaN 1356998400000
expect(Date.parse("2012-04-04T05:02:02.170Z")).toBe(1333515722170); //1333515722170 1333515722170 1333515722170 1333515722170 1333515722170
expect(Date.parse("2012-04-04T24:00:00.000Z")).toBe(1333584000000); //NaN 1333584000000 1333584000000 1333584000000 1333584000000
expect(Date.parse("2012-04-04T24:00:00.500Z")).toBeFalsy(); //NaN NaN 1333584000500 1333584000500 NaN
expect(Date.parse("2012-12-31T10:08:60.000Z")).toBeFalsy(); //NaN NaN NaN NaN 1356948540000
expect(Date.parse("2012-13-01T12:00:00.000Z")).toBeFalsy(); //NaN NaN NaN NaN NaN
expect(Date.parse("2012-12-32T12:00:00.000Z")).toBeFalsy(); //NaN NaN NaN NaN NaN
expect(Date.parse("2012-12-31T25:00:00.000Z")).toBeFalsy(); //NaN NaN NaN NaN NaN
expect(Date.parse("2012-12-31T24:01:00.000Z")).toBeFalsy(); //NaN NaN NaN 1356998460000 NaN
expect(Date.parse("2012-12-31T12:60:00.000Z")).toBeFalsy(); //NaN NaN NaN NaN NaN
expect(Date.parse("2012-12-31T12:00:60.000Z")).toBeFalsy(); //NaN NaN NaN NaN 1356955260000
expect(Date.parse("2012-00-31T23:59:59.000Z")).toBeFalsy(); //NaN NaN NaN NaN NaN
expect(Date.parse("2012-12-00T23:59:59.000Z")).toBeFalsy(); //NaN NaN NaN NaN NaN
expect(Date.parse("2012-02-29T12:00:00.000Z")).toBe(1330516800000); //1330516800000 1330516800000 1330516800000 1330516800000 1330516800000
expect(Date.parse("2011-02-29T12:00:00.000Z")).toBeFalsy(); //1298980800000 NaN NaN 1298980800000 NaN
expect(Date.parse("2011-03-01T12:00:00.000Z")).toBe(1298980800000); //1298980800000 1298980800000 1298980800000 1298980800000 1298980800000
// extended years:
expect(Date.parse("0000-01-01T00:00:00.000Z")).toBe(-621672192e5); //-621672192e5 -621672192e5 -621672192e5 -621672192e5 -621672192e5
expect(Date.parse("+275760-09-13T00:00:00.000Z")).toBe(8.64e15); //8.64e15 NaN 8.64e15 8.64e15 8.64e15
expect(Date.parse("-271821-04-20T00:00:00.000Z")).toBe(-8.64e15); //-8.64e15 NaN -8.64e15 -8.64e15 -8.6400000864e15
expect(Date.parse("+275760-09-13T00:00:00.001Z")).toBeFalsy(); //NaN NaN NaN 8.64e15 + 1 8.64e15 + 1
expect(Date.parse("-271821-04-19T23:59:59.999Z")).toBeFalsy(); //NaN NaN NaN -8.64e15 - 1 -8.6400000864e15 - 1
// https://github.com/kriskowal/es5-shim/issues/80 Safari bug with leap day
expect(Date.parse("2034-03-01T00:00:00.000Z") -
Date.parse("2034-02-27T23:59:59.999Z")).toBe(86400001); //86400001 86400001 86400001 86400001 1
// Time Zone Offset
expect(Date.parse("2012-01-29T12:00:00.000+01:00")).toBe(132783480e4);//132783480e4 132783480e4 132783480e4 132783480e4 132783480e4
expect(Date.parse("2012-01-29T12:00:00.000-00:00")).toBe(132783840e4);//132783840e4 132783840e4 132783840e4 132783840e4 132783840e4
expect(Date.parse("2012-01-29T12:00:00.000+00:00")).toBe(132783840e4);//132783840e4 132783840e4 132783840e4 132783840e4 132783840e4
expect(Date.parse("2012-01-29T12:00:00.000+23:59")).toBe(132775206e4);//132775206e4 132775206e4 132775206e4 132775206e4 132775206e4
expect(Date.parse("2012-01-29T12:00:00.000-23:59")).toBe(132792474e4);//132792474e4 132792474e4 132792474e4 132792474e4 132792474e4
expect(Date.parse("2012-01-29T12:00:00.000+24:00")).toBeFalsy(); //NaN 1327752e6 NaN 1327752000000 1327752000000
expect(Date.parse("2012-01-29T12:00:00.000+24:01")).toBeFalsy(); //NaN NaN NaN 1327751940000 1327751940000
expect(Date.parse("2012-01-29T12:00:00.000+24:59")).toBeFalsy(); //NaN NaN NaN 1327748460000 1327748460000
expect(Date.parse("2012-01-29T12:00:00.000+25:00")).toBeFalsy(); //NaN NaN NaN NaN NaN
expect(Date.parse("2012-01-29T12:00:00.000+00:60")).toBeFalsy(); //NaN NaN NaN NaN NaN
expect(Date.parse("-271821-04-20T00:00:00.000+00:01")).toBeFalsy(); //NaN NaN NaN -864000000006e4 -864000008646e4
expect(Date.parse("-271821-04-20T00:01:00.000+00:01")).toBe(-8.64e15);//-8.64e15 NaN -8.64e15 -8.64e15 -864000008640e4
// When time zone is missed, local offset should be used (ES 5.1 bug)
// see https://bugs.ecmascript.org/show_bug.cgi?id=112
var tzOffset = Number(new Date(1970, 0));
// same as (new Date().getTimezoneOffset() * 60000)
expect(Date.parse('1970-01-01T00:00:00')).toBe(tzOffset); //tzOffset 0 0 0 NaN
});
});
describe("toISOString", function () {
// TODO: write the rest of the test.
it('should support extended years', function () {
expect(new Date(-62198755200000).toISOString().indexOf('-000001-01-01')).toBe(0);
expect(new Date(8.64e15).toISOString().indexOf('+275760-09-13')).toBe(0);
});
it('should return correct dates', function () {
expect(new Date(-1).toISOString()).toBe('1969-12-31T23:59:59.999Z');// Safari 5.1.5 "1969-12-31T23:59:59.-01Z"
expect(new Date(-3509827334573292).toISOString()).toBe('-109252-01-01T10:37:06.708Z'); // Opera 11.61/Opera 12 bug with Date#getUTCMonth
});
});
describe("toJSON", function () {
// Opera 11.6x/12 bug
it('should call toISOString', function () {
var date = new Date(0);
date.toISOString = function () {
return 1;
};
expect(date.toJSON()).toBe(1);
});
it('should return null for not finite dates', function () {
var date = new Date(NaN),
json;
try {
json = date.toJSON();
} catch (e) {}
expect(json).toBe(null);
});
it('should return the isoString when stringified', function () {
var date = new Date();
expect(JSON.stringify(date.toISOString())).toBe(JSON.stringify(date));
})
});
});

View File

@ -0,0 +1,147 @@
describe('Function', function() {
"use strict";
describe('bind', function() {
var actual, expected,
testSubject;
testSubject = {
push: function(o) {
this.a.push(o);
}
};
function func() {
Array.prototype.forEach.call(arguments, function(a) {
this.push(a);
}, this);
return this;
};
beforeEach(function() {
actual = [];
testSubject.a = [];
});
it('binds properly without a context', function() {
var context;
testSubject.func = function() {
context = this;
}.bind();
testSubject.func();
expect(context).toBe(function() {return this}.call());
});
it('binds properly without a context, and still supplies bound arguments', function() {
var a, context;
testSubject.func = function() {
a = Array.prototype.slice.call(arguments);
context = this;
}.bind(undefined, 1,2,3);
testSubject.func(1,2,3);
expect(a).toEqual([1,2,3,1,2,3]);
expect(context).toBe(function() {return this}.call());
});
it('binds a context properly', function() {
testSubject.func = func.bind(actual);
testSubject.func(1,2,3);
expect(actual).toEqual([1,2,3]);
expect(testSubject.a).toEqual([]);
});
it('binds a context and supplies bound arguments', function() {
testSubject.func = func.bind(actual, 1,2,3);
testSubject.func(4,5,6);
expect(actual).toEqual([1,2,3,4,5,6]);
expect(testSubject.a).toEqual([]);
});
it('returns properly without binding a context', function() {
testSubject.func = function() {
return this;
}.bind();
var context = testSubject.func();
expect(context).toBe(function() {return this}.call());
});
it('returns properly without binding a context, and still supplies bound arguments', function() {
var context;
testSubject.func = function() {
context = this;
return Array.prototype.slice.call(arguments);
}.bind(undefined, 1,2,3);
actual = testSubject.func(1,2,3);
expect(context).toBe(function() {return this}.call());
expect(actual).toEqual([1,2,3,1,2,3]);
});
it('returns properly while binding a context properly', function() {
var ret;
testSubject.func = func.bind(actual);
ret = testSubject.func(1,2,3);
expect(ret).toBe(actual);
expect(ret).not.toBe(testSubject);
});
it('returns properly while binding a context and supplies bound arguments', function() {
var ret;
testSubject.func = func.bind(actual, 1,2,3);
ret = testSubject.func(4,5,6);
expect(ret).toBe(actual);
expect(ret).not.toBe(testSubject);
});
it('passes the correct arguments as a constructor', function() {
var ret, expected = { name: "Correct" };
testSubject.func = function(arg) {
return arg;
}.bind({ name: "Incorrect" });
ret = new testSubject.func(expected);
expect(ret).toBe(expected);
});
it('returns the return value of the bound function when called as a constructor', function () {
var oracle = [1, 2, 3];
var subject = function () {
return oracle;
}.bind(null);
var result = new subject;
expect(result).toBe(oracle);
});
it('returns the correct value if constructor returns primitive', function() {
var oracle = [1, 2, 3];
var subject = function () {
return oracle;
}.bind(null);
var result = new subject;
expect(result).toBe(oracle);
oracle = {};
result = new subject;
expect(result).toBe(oracle);
oracle = function(){};
result = new subject;
expect(result).toBe(oracle);
oracle = "asdf";
result = new subject;
expect(result).not.toBe(oracle);
oracle = null;
result = new subject;
expect(result).not.toBe(oracle);
oracle = true;
result = new subject;
expect(result).not.toBe(oracle);
oracle = 1;
result = new subject;
expect(result).not.toBe(oracle);
});
it('returns the value that instance of original "class" when called as a constructor', function() {
var classA = function(x) {
this.name = x || "A";
}
var classB = classA.bind(null, "B");
var result = new classB;
expect(result instanceof classA).toBe(true);
expect(result instanceof classB).toBe(true);
});
});
});

View File

@ -0,0 +1,84 @@
describe('Object', function () {
"use strict";
describe("Object.keys", function () {
var obj = {
"str": "boz",
"obj": { },
"arr": [],
"bool": true,
"num": 42,
"null": null,
"undefined": undefined
};
var loopedValues = [];
for (var k in obj) {
loopedValues.push(k);
}
var keys = Object.keys(obj);
it('should have correct length', function () {
expect(keys.length).toBe(7);
});
it('should return an Array', function () {
expect(Array.isArray(keys)).toBe(true);
});
it('should return names which are own properties', function () {
keys.forEach(function (name) {
expect(obj.hasOwnProperty(name)).toBe(true);
});
});
it('should return names which are enumerable', function () {
keys.forEach(function (name) {
expect(loopedValues.indexOf(name)).toNotBe(-1);
})
});
it('should throw error for non object', function () {
var e = {};
expect(function () {
try {
Object.keys(42)
} catch (err) {
throw e;
}
}).toThrow(e);
});
});
describe("Object.isExtensible", function () {
var obj = { };
it('should return true if object is extensible', function () {
expect(Object.isExtensible(obj)).toBe(true);
});
it('should return false if object is not extensible', function () {
expect(Object.isExtensible(Object.preventExtensions(obj))).toBe(false);
});
it('should return false if object is seal', function () {
expect(Object.isExtensible(Object.seal(obj))).toBe(false);
});
it('should return false if object is freeze', function () {
expect(Object.isExtensible(Object.freeze(obj))).toBe(false);
});
it('should throw error for non object', function () {
var e1 = {};
expect(function () {
try {
Object.isExtensible(42)
} catch (err) {
throw e1;
}
}).toThrow(e1);
});
});
});

View File

@ -0,0 +1,24 @@
describe('String', function() {
"use strict";
describe("trim", function() {
var test = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFFHello, World!\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF";
it('trims all ES5 whitespace', function() {
expect(test.trim()).toEqual("Hello, World!");
expect(test.trim().length).toEqual(13);
});
});
describe("split", function() {
var test = "ab";
it('If "separator" is undefined must return Array with one String - "this" string', function() {
expect(test.split()).toEqual([test]);
expect(test.split(void 0)).toEqual([test]);
});
it('If "separator" is undefined and "limit" set to 0 must return Array[]', function() {
expect(test.split(void 0, 0)).toEqual([]);
});
});
});