This repository was archived by the owner on Oct 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathcw-2.js
More file actions
501 lines (453 loc) · 14.8 KB
/
Copy pathcw-2.js
File metadata and controls
501 lines (453 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
try {
var util = require('util'),
deepEquals = require('lodash').isEqual,
Promise = require("bluebird");
require('./chai-display');
var fnToString = Function.toString;
Function.prototype.toString = function() {
switch (this) {
case Test.expect:
case Test.randomNumber:
case Test.randomize:
case Test.randomToken:
return '[Codewars Code]';
default:
return fnToString.call(this);
}
};
var describing = [],
async = false,
asyncIts = null,
asyncDone = null,
failed = [],
beforeCallbacks = [],
afterCallbacks = [],
alwaysExplain = false;
process.on('uncaughtException', function(err) {
if (async) {
Test.handleError(err);
if (asyncDone) asyncDone();
}
});
var describeNext = function() {
if (asyncIts.length > 0) {
asyncIts.shift()();
}
else if (describing.length) {
describing.pop()();
}
};
var _expect = function(passed, failMsg, options) {
options = options || {};
if (passed) {
var successMsg = "Test Passed";
if (options.successMsg) {
successMsg += ": " + options.successMsg;
}
Test.display.write("PASSED", successMsg);
if (options.passed) {
options.passed(successMsg, options);
}
}
else {
failMsg = failMsg || 'Value is not what was expected';
Test.display.write("FAILED", failMsg);
if (options.failed) {
options.failed(failMsg, options);
}
var error = new Test.Error(failMsg);
if (describing) {
failed.push(error);
}
else {
throw error;
}
}
};
// convenience method for adding a default failed callback to an options
var _failed = function(options, callback) {
options = options || {};
options.failed = options.failed || callback;
return options;
};
var Test = {
// when called, it will set a flag to cause all failed tests to explain the expected/actual results
explainAll: function(mode) {
alwaysExplain = mode || true;
},
display: require('./display'),
// we use this instead of util.inspect so that we can support the indent option and json options
stringify: function(obj, indent) {
var cache = [];
return JSON.stringify(obj, function(key, value) {
if (typeof value === 'object' && value !== null) {
// Circular reference found, discard key
if (cache.indexOf(value) !== -1) return "[Circular]";
}
// Store value in our collection
cache.push(value);
return value;
}, indent);
},
// backwards compatibility
format: function(obj, options) {
Test.display.format(obj, options);
},
inspect: function(obj) {
// format arrays ourselves since long arrays end up getting broken out into separate lines, which is often a
// bad format for typical use cases.
if (Array.isArray(obj)) {
return "[" + obj.map(function(v) {
return Test.inspect(v);
}).join(", ") + "]";
}
return util.inspect(obj);
},
log: function(msg, opts) {
Test.display.log(msg, opts);
},
describe: function(msg, asyncTimeout, fn) {
return new Promise(function(resolve, reject) {
if (!fn) {
fn = asyncTimeout;
asyncTimeout = false;
}
else if (asyncTimeout === true) {
asyncTimeout = 2000; // default timeout to 2 seconds
}
var start = new Date();
try {
async = asyncTimeout;
asyncIts = [];
describing.push(function() {
var ms = new Date() - start;
Test.display.write("COMPLETEDIN", ms);
// TODO: right now before/after blocks don't work very well with multi level describes so they
// should only be used at the top level
if (!describing.length) {
beforeCallbacks = [];
afterCallbacks = [];
}
if (failed.length > 0) throw failed[0];
async = false;
resolve();
});
Test.display.write("DESCRIBE", msg);
fn();
if (async) describeNext();
}
catch (ex) {
Test.handleError(ex);
}
finally {
if (!async && describing.length) describing.pop()();
}
});
},
it: function(msg, fn) {
if (!describing.length) throw '"it" calls must be invoked within a parent "describe" context';
var asyncIt = (async && fn.length > 0);
var begin = function() {
Test.display.write("IT", msg);
beforeCallbacks.forEach(function(cb) {
cb();
});
var start = new Date(),
timeout,
done = function() {
if (timeout) clearTimeout(timeout);
var ms = new Date() - start;
Test.display.write("COMPLETEDIN", ms);
afterCallbacks.forEach(function(cb) {
cb();
});
done = null;
if (asyncIt) describeNext();
};
if (asyncIt) {
timeout = setTimeout(function() {
if (done) {
throw "`it` function timed out. Function ran longer than " + async + "ms";
}
}, async);
asyncDone = done;
}
try {
fn(asyncIt ? done : undefined);
}
catch (ex) {
Test.handleError(ex);
}
finally {
if (!asyncIt) done();
}
};
// if async then we queue everything up first
if (async) {
asyncIts.push(begin);
}
// otherwise just run it
else {
begin();
}
},
before: function(cb) {
beforeCallbacks.push(cb);
},
after: function(cb) {
afterCallbacks.push(cb);
},
// handles an error and writes the appropriate output. If a function is provided it will handle the error
// if the function errors, and then rethrow the exception
handleError: function(ex) {
if (typeof ex == "function") {
try {
ex();
}
catch (ex) {
this.handleError(ex);
throw ex;
}
}
else if (ex.name == 'AssertionError') {
this.fail(ex.message);
}
else if (ex.name != "TestError") {
Test.display.write("ERROR", Test.trace(ex));
}
},
// clean up the stack trace of the exception so that it doesn't give confusing results.
// Results would be confusing because the user submitted code is compiled into a script where
// additional code is injected and line numbers will not match.
trace: function(ex) {
return (ex.stack || ex.toString() || '')
.toString()
// remove file names (ie: (/cli-runner/...))
.replace(/\s\(.*\)/g, '')
// remove at [eval] statements
.replace(/(at)*( Object.)*\s*[(]?\[eval\].*(:\d*)*[)]?\n/g, '')
// remove stack trace beyond the Module information
.replace(/at Module[\w\s.:\d\n]*/g, '')
// remove at Object.<anonymous>
.replace(/\t*at Object.<\w*>\n/g, '')
// handleError is used to wrap top level code, so lets remove it so that it doesn't
// confuse users who won't understand why it is there.
.replace('at Object.Test.handleError', '');
},
pass: function() {
_expect(true);
},
fail: function(message) {
_expect(false, message);
},
expect: function(passed, message, options) {
_expect(passed, message, options);
},
assertSimilar: function(actual, expected, msg, options) {
this.assertEquals(Test.inspect(actual), Test.inspect(expected), msg, options);
},
assertNotSimilar: function(actual, expected, msg, options) {
this.assertNotEquals(Test.inspect(actual), Test.inspect(expected), msg, options);
},
assertEquals: function(actual, expected, msg, options) {
if (typeof(msg) == 'object') {
options = msg;
msg = null;
}
if (actual !== expected) {
var explain = options && options.explain ? options.explain : alwaysExplain;
if (explain) {
Test.expect(false, msg || "Values should be equal", _failed(options, function() {
Test.display.explain(actual, expected, {mode: explain, className: 'failed'});
}));
}
else {
Test.expect(false, Test.display.message('Expected: ' + Test.inspect(expected) + ', instead got: ' + Test.inspect(actual), msg));
}
}
else {
options = options || {};
options.successMsg = options.successMsg || 'Value == ' + Test.inspect(expected);
Test.expect(true, null, options);
}
},
assertNotEquals: function(actual, expected, msg, options) {
if (typeof(msg) == 'object') {
options = msg;
msg = null;
}
if (actual === expected) {
var explain = options && options.explain ? options.explain : alwaysExplain;
if (explain) {
Test.expect(false, msg || "Values should not equal each other", _failed(options, function() {
Test.display.explain(actual, expected, {mode: explain, className: 'failed'});
}));
}
else {
msg = Test.display.message('Values should not be equal: ' + Test.inspect(actual), msg);
Test.expect(false, msg, options);
}
}
else {
options = options || {};
options.successMsg = options.successMsg || 'Value != ' + Test.inspect(expected);
Test.expect(true, null, options);
}
},
assertDeepEquals: function(actual, expected, msg, options) {
if (deepEquals(actual, expected)) {
options = options || {};
options.successMsg = options.successMsg || 'Value deep equals ' + Test.inspect(expected);
Test.expect(true, null, options);
}
else {
msg = Test.display.message('Expected: ' + Test.inspect(expected) + ', instead got: ' + Test.inspect(actual), msg);
Test.expect(false, msg, options);
}
},
assertNotDeepEquals: function(actual, expected, msg, options) {
if (!deepEquals(actual, expected)) {
options = options || {};
options.successMsg = options.successMsg || 'Value not deep equals ' + Test.inspect(expected);
Test.expect(true, null, options);
}
else {
msg = Test.display.message('Value should not deep equal ' + Test.inspect(actual), msg);
Test.expect(false, msg, options);
}
},
assertApproxEquals: function(actual, expected, msg, options) {
// Compares two floating point values and checks whether they are approximately equal to each other
options = options || {};
msg = Test.display.message('Expected actual value ' + actual + ' to approximately equal expected value ' + expected + ' (accepted relative error: 1e-9)', msg);
if (Math.abs(expected) <= 1) {
Test.expect(Math.abs(expected - actual) <= 1e-9, msg, options);
}
else {
Test.expect(Math.abs((expected - actual) / expected) <= 1e-9, msg, options);
}
},
assertNotApproxEquals: function(actual, unexpected, msg, options) {
// Compares two floating point values and checks whether they are sufficiently different from each other
options = options || {};
msg = Test.display.message('Actual value ' + actual + ' should not approximately equal unexpected value ' + unexpected + ' (rejected relative error: 1e-9)', msg);
if (Math.abs(unexpected) <= 1) {
Test.expect(Math.abs(unexpected - actual) > 1e-9, msg, options);
}
else {
Test.expect(Math.abs((unexpected - actual) / unexpected) > 1e-9, msg, options);
}
},
assertContains: function(actual, expected, msg, options) {
if (actual.indexOf(expected) >= 0) {
options = options || {};
options.successMsg = options.successMsg || 'Value ' + Test.inspect(actual) + ' contains ' + Test.inspect(expected);
Test.expect(true, null, options);
}
else {
msg = Test.display.message('Value ' + Test.inspect(actual) + ' should contain ' + Test.inspect(expected), msg);
Test.expect(false, msg, options);
}
},
assertNotContains: function(actual, expected, msg, options) {
if (actual.indexOf(expected) === -1) {
options = options || {};
options.successMsg = options.successMsg || 'Value ' + Test.inspect(actual) + ' does not contain ' + Test.inspect(expected);
Test.expect(true, null, options);
}
else {
msg = Test.display.message('Value ' + Test.inspect(actual) + ' should not contain ' + Test.inspect(expected), msg);
Test.expect(false, msg, options);
}
},
expectNoError: function(msg, fn) {
if (!fn) {
fn = msg;
msg = 'Unexpected error was thrown';
}
try {
fn();
Test.expect(true);
}
catch (ex) {
if (ex.name == 'TestError') {
throw ex;
}
else {
msg += ': ' + ex.toString();
Test.expect(false, msg);
}
}
},
expectError: function(msg, fn, options) {
if (!fn) {
fn = msg;
msg = 'Expected an error to be thrown';
}
var passed = false;
try {
fn();
}
catch (ex) {
console.log('<b>Expected error was thrown:</b> ' + ex.toString());
passed = true;
}
Test.expect(passed, msg, options);
},
randomNumber: function() {
return Math.floor(Math.random() * 101);
},
randomToken: function() {
return Math.random().toString(36).substr(8);
},
randomize: function(array) {
var arr = array.concat(), i = arr.length, j, x;
while (i) {
j = (Math.random() * i) | 0;
x = arr[--i];
arr[i] = arr[j];
arr[j] = x;
}
return arr;
},
sample: function(array) {
return array[~~(array.length * Math.random())];
},
escapeHtml: function(html) {
return Test.display.escapeHtml(html);
},
Error: function(message) {
this.name = "TestError";
this.message = (message || "");
}
};
// Test.Error.prototype = require('assert').AssertionError.prototype;
Test.Error.prototype = Error.prototype;
Object.freeze(Test.display);
Object.freeze(Test);
Object.defineProperty(global, 'Test', {
writable: false,
configurable: false,
value: Test
});
Object.defineProperty(global, 'describe', {
writable: false,
value: Test.describe
});
Object.defineProperty(global, 'it', {
writable: false,
value: Test.it
});
Object.defineProperty(global, 'before', {
writable: false,
value: Test.before
});
Object.defineProperty(global, 'after', {
writable: false,
value: Test.after
});
}
catch (ex) {
console.error(ex);
throw "Failed to load core API methods";
}