UNPKG

1.96 kBJavaScriptView Raw
1'use strict';
2
3var handleCurry = require('./utils/handleCurry'),
4 isFinitePredicate = require('./finite'),
5 isNumber = require('./number');
6
7/**
8 * Checks whether a value is a number and it's divisible by divisor with given remainder
9 * In other words value % div === remainder
10 *
11 * **Aliases** _divisibleByWithRemainder_, _divByWithRemainder_
12 *
13 * @function divisibleWithRemainder
14 *
15 * @example
16 * var is = require('predicates');
17 *
18 * is.divisibleWithRemainder(3, 2, 5); // true since 5%3 === 2
19 * is.divisibleWithRemainder(3, 2)(5); // true
20 * is.divisibleWithRemainder(3, 1, 5); // false since 5%3 !== 1
21 *
22 * var isEven = is.divisibleWithRemainder(2, 1);
23 *
24 * isEven(1); // true
25 * isEven(2); // false
26 * isEven(3); // true
27 *
28 * *
29 * @param {Number} divisor
30 * @param {Number} remainder
31 * @param {Number} [value]
32 * @throws {Error} if less than 2 arguments provided
33 * @throws {Error} if the divisor is 0
34 * @throws {Error} if the remainder is greater than the divisor
35 * @throws {TypeError} if the divisor is not a finite number
36 * @throws {TypeError} if the remainder is not a finite number
37 * @returns {(Boolean|Predicate)} returns bool if at least 3 arguments provided, otherwise a predicate
38 */
39module.exports = function divisibleWithRemainder(divisor, remainder) {
40 if (arguments.length < 2) {
41 throw new Error('Missing remainder');
42 }
43
44 if (!isFinitePredicate(divisor)) {
45 throw new TypeError('Divisor is not a finite number');
46 }
47
48 if (divisor === 0) {
49 throw new Error('Divisor cannot be 0');
50 }
51
52 if (!isFinitePredicate(remainder)) {
53 throw new TypeError('Remainder is not a finite number');
54 }
55
56 if (remainder >= divisor) {
57 throw new Error('Remainder cannot be greater than divisor');
58 }
59
60 return handleCurry.call(this, arguments, function isDivisibleByWithRemainderTest(value) {
61 return isNumber(value) && value % divisor === remainder;
62 }, 2);
63};
\No newline at end of file