assert.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. module.exports = (function(){
  3. var AssertionError = (function() {
  4. function AssertionError(a) {
  5. this.constructor$(a);
  6. this.message = a;
  7. this.name = "AssertionError";
  8. }
  9. AssertionError.prototype = new Error();
  10. AssertionError.prototype.constructor = AssertionError;
  11. AssertionError.prototype.constructor$ = Error;
  12. return AssertionError;
  13. })();
  14. function getParams(args) {
  15. var params = [];
  16. for (var i = 0; i < args.length; ++i) params.push("arg" + i);
  17. return params;
  18. }
  19. function nativeAssert(callName, args, expect) {
  20. try {
  21. var params = getParams(args);
  22. var constructorArgs = params;
  23. constructorArgs.push("return " +
  24. callName + "("+ params.join(",") + ");");
  25. var fn = Function.apply(null, constructorArgs);
  26. return fn.apply(null, args);
  27. } catch (e) {
  28. if (!(e instanceof SyntaxError)) {
  29. throw e;
  30. } else {
  31. return expect;
  32. }
  33. }
  34. }
  35. return function assert(boolExpr, message) {
  36. if (boolExpr === true) return;
  37. if (typeof boolExpr === "string" &&
  38. boolExpr.charAt(0) === "%") {
  39. var nativeCallName = boolExpr;
  40. var $_len = arguments.length;var args = new Array(Math.max($_len - 2, 0)); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];};
  41. if (nativeAssert(nativeCallName, args, message) === message) return;
  42. message = (nativeCallName + " !== " + message);
  43. }
  44. var ret = new AssertionError(message);
  45. if (Error.captureStackTrace) {
  46. Error.captureStackTrace(ret, assert);
  47. }
  48. throw ret;
  49. };
  50. })();