assert.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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($_len - 2); 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. })();