All files array-utils.js

100% Statements 8/8
100% Branches 5/5
100% Functions 6/6
100% Lines 7/7
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                                                4x 8x                                   6x                           1x 2x 1x 1x        
/* 
 * Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/**
 * Flattens an arrays of arrays into a single array.
 * 
 * @param {Array} array
 * @return {Array} Flattened array.
 */
export function flatten(array) {
 
	return array.reduce((accumulator, value) => {
		return accumulator.concat(Array.isArray(value) ? flatten(value) : value);
	}, []);
}
 
/**
 * Creates an array of numbers from the starting value (inclusive) to the end
 * (exclusive), with an optional step (the gap between values).
 * 
 * @param {Number} start
 *   The value to start at, the first item in the returned array.
 * @param {Number} end
 *   The value to end with, the last item in the returned array.
 * @param {Number} [step=1]
 *   The increment/gap between values, defaults to 1.
 * @return {Array} An array encompassing the given range.
 */
export function range(start, end, step = 1) {
 
	return Array.apply(0, Array(Math.ceil((end - start) / step))).map((empty, index) => index * step + start);
}
 
/**
 * Remove and return the first item from `array` that matches the predicate
 * function.
 * 
 * @param {Array} array
 * @param {Function} predicate
 *   Invoked with the array item.
 * @return {Object} The matching item, or `null` if no match was found.
 */
export function remove(array, predicate) {
 
	return array.find((item, index) => {
		if (predicate(item)) {
			array.splice(index, 1);
			return item;
		}
	});
}