/
index.js
69 lines (59 loc) · 1.95 KB
/
index.js
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
'use strict';
var nextTick = require('just-next-tick');
var isCallable = require('is-callable');
/*
* Big Integer Maximum
*
* Pass in two strings that are otherwise valid integers, positive or negative.
* No leading zeroes.
*/
var digits = /^-?[0-9]+$/;
var leadingZeroes = /^-?0+[^0]+$/;
var bigIntegerMax = function bigIntegerMaximum(numberA, numberB) {
var aNegative = numberA.charAt(0) === '-';
var bNegative = numberB.charAt(0) === '-';
var bothNegative = aNegative && bNegative;
var largest = numberA;
if (numberA !== numberB) {
var lengthA = numberA.length;
var lengthB = numberB.length;
if (bothNegative) {
if (lengthB < lengthA) {
// negative number with the least digits is largest
largest = numberB;
} else if (lengthA === lengthB) {
// lengths are the same; both negative
largest = numberA < numberB ? numberA : numberB;
}
} else if (aNegative || bNegative) {
// signs are different
if (aNegative) {
largest = numberB;
}
} else /* both positive */ if (lengthA < lengthB) {
// positive number with the most digits is largest
largest = numberB;
} else if (lengthA === lengthB) {
// lengths are the same; both positive
largest = numberA > numberB ? numberA : numberB;
}
}
return largest;
};
var dispatcher = function (numberA, numberB, callback) {
if (typeof numberA !== 'string' || typeof numberB !== 'string') {
throw new TypeError('both arguments must be strings');
} else if (!digits.test(numberA) || !digits.test(numberB)) {
throw new TypeError('both strings must be valid positive, negative, or zero integers');
} else if (leadingZeroes.test(numberA) || leadingZeroes.test(numberB)) {
throw new TypeError('both strings must have no leading zeroes');
}
if (isCallable(callback)) {
return nextTick(function () {
callback(null, bigIntegerMax(numberA, numberB));
});
}
return bigIntegerMax(numberA, numberB);
};
dispatcher.method = bigIntegerMax;
module.exports = dispatcher;