some_by.js (2526B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isCollection = require( '@stdlib/assert/is-collection' ); 24 var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive; 25 var isFunction = require( '@stdlib/assert/is-function' ); 26 27 28 // MAIN // 29 30 /** 31 * Tests whether a collection contains at least `n` elements which pass a test implemented by a predicate function. 32 * 33 * @param {Collection} collection - input collection 34 * @param {PositiveInteger} n - number of elements 35 * @param {Function} predicate - test function 36 * @param {*} [thisArg] - execution context 37 * @throws {TypeError} first argument must be a collection 38 * @throws {TypeError} second argument must be a positive integer 39 * @throws {TypeError} third argument must be a function 40 * @returns {boolean} boolean indicating whether a collection contains at least `n` elements which pass a test 41 * 42 * @example 43 * function isNegative( v ) { 44 * return ( v < 0 ); 45 * } 46 * 47 * var arr = [ 1, 2, -3, 4, -1 ]; 48 * 49 * var bool = someBy( arr, 2, isNegative ); 50 * // returns true 51 */ 52 function someBy( collection, n, predicate, thisArg ) { 53 var count; 54 var out; 55 var len; 56 var i; 57 if ( !isCollection( collection ) ) { 58 throw new TypeError( 'invalid argument. First argument must be a collection. Value: `'+collection+'`.' ); 59 } 60 if ( !isPositiveInteger( n ) ) { 61 throw new TypeError( 'invalid argument. Second argument must be a positive integer. Value: `'+n+'`.' ); 62 } 63 if ( !isFunction( predicate ) ) { 64 throw new TypeError( 'invalid argument. Third argument must be a function. Value: `'+predicate+'`.' ); 65 } 66 len = collection.length; 67 count = 0; 68 for ( i = 0; i < len; i++ ) { 69 out = predicate.call( thisArg, collection[ i ], i, collection ); 70 if ( out ) { 71 count += 1; 72 if ( count === n ) { 73 return true; 74 } 75 } 76 // Account for dynamically resizing a collection: 77 len = collection.length; 78 } 79 return false; 80 } 81 82 83 // EXPORTS // 84 85 module.exports = someBy;