UNPKG

1.18 kBJavaScriptView Raw
1'use strict';
2
3var isArray = require('./array'),
4 handleCurry = require('./utils/handleCurry');
5
6/**
7 * Checks whether a value exists in collection
8 * Values are compared using === operator
9 *
10 * @function in
11 *
12 * @example
13 * var is = require('predicates');
14 *
15 * var isImage = is.in(['image/gif', 'image/jpeg']);
16 * // same as
17 * // var isImage = is.oneOf('image/gif', 'image/jpeg');
18 *
19 * isImage('image/jpeg'); // true
20 * // same as
21 * is.in(['image/gif', 'image/jpeg'], 'image/jpeg'); // true
22 *
23 * isImage('text/html'); // false
24 *
25 * @param {Array} collection of allowed values
26 * @param {*} [value]
27 * @throws {TypeError} if collection is not an array
28 * @throws {Error} if collection is empty
29 * @returns {(Boolean|Predicate)} bool if at least two arguments provided, otherwise a predicate
30 */
31module.exports = function isIn(collection) {
32 if (!isArray(collection)) {
33 throw new TypeError('Collection must be an array');
34 }
35
36 if (collection.length === 0) {
37 throw new Error('Collection cannot be empty');
38 }
39
40 return handleCurry.call(this, arguments, function isInPredicate(value) {
41 return collection.indexOf(value) !== -1;
42 });
43};