count_by.js (2528B)
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 isFunction = require( '@stdlib/assert/is-function' ); 25 var hasOwnProp = require( '@stdlib/assert/has-own-property' ); 26 var validate = require( './validate.js' ); 27 28 29 // MAIN // 30 31 /** 32 * Groups values according to an indicator function and returns group counts. 33 * 34 * @param {Collection} collection - input collection 35 * @param {Options} [options] - function options 36 * @param {*} [options.thisArg] - execution context 37 * @param {Function} indicator - indicator function specifying which group an element in the input collection belongs to 38 * @throws {TypeError} first argument must be a collection 39 * @throws {TypeError} options argument must be an object 40 * @throws {TypeError} last argument must be a function 41 * @throws {TypeError} must provide valid options 42 * @returns {Object} counts 43 * 44 * @example 45 * function indicator( v ) { 46 * return v[ 0 ]; 47 * } 48 * var arr = [ 'beep', 'boop', 'foo', 'bar' ]; 49 * 50 * var out = countBy( arr, indicator ); 51 * // returns { 'b': 3, 'f': 1 } 52 */ 53 function countBy( collection, options, indicator ) { 54 var thisArg; 55 var opts; 56 var err; 57 var out; 58 var len; 59 var cb; 60 var g; 61 var i; 62 if ( !isCollection( collection ) ) { 63 throw new TypeError( 'invalid argument. First argument must be a collection. Value: `'+collection+'`.' ); 64 } 65 opts = {}; 66 if ( arguments.length === 2 ) { 67 cb = options; 68 } else { 69 err = validate( opts, options ); 70 if ( err ) { 71 throw err; 72 } 73 cb = indicator; 74 } 75 if ( !isFunction( cb ) ) { 76 throw new TypeError( 'invalid argument. Last argument must be a function. Value: `'+cb+'`.' ); 77 } 78 thisArg = opts.thisArg; 79 len = collection.length; 80 out = {}; 81 for ( i = 0; i < len; i++ ) { 82 g = cb.call( thisArg, collection[ i ], i ); 83 if ( hasOwnProp( out, g ) ) { 84 out[ g ] += 1; 85 } else { 86 out[ g ] = 1; 87 } 88 } 89 return out; 90 } 91 92 93 // EXPORTS // 94 95 module.exports = countBy;