UNPKG

ml-array-sequential-fill

Version:
91 lines (74 loc) 2.45 kB
import { isAnyArray } from 'is-any-array'; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * Fill an array with sequential numbers * @param {Array<number>} [input] - optional destination array (if not provided a new array will be created) * @param {object} [options={}] * @param {number} [options.from=0] - first value in the array * @param {number} [options.to=10] - last value in the array * @param {number} [options.size=input.length] - size of the array (if not provided calculated from step) * @param {number} [options.step] - if not provided calculated from size * @return {Array<number>} */ function sequentialFill() { var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (_typeof(input) === 'object' && !isAnyArray(input)) { options = input; input = []; } if (!isAnyArray(input)) { throw new TypeError('input must be an array'); } var _options = options, _options$from = _options.from, from = _options$from === void 0 ? 0 : _options$from, _options$to = _options.to, to = _options$to === void 0 ? 10 : _options$to, _options$size = _options.size, size = _options$size === void 0 ? input.length : _options$size, step = _options.step; if (size !== 0 && step) { throw new Error('step is defined by the array size'); } if (!size) { if (step) { size = Math.floor((to - from) / step) + 1; } else { size = to - from + 1; } } if (!step && size) { step = (to - from) / (size - 1); } if (Array.isArray(input)) { // only works with normal array input.length = 0; for (var i = 0; i < size; i++) { input.push(from); from += step; } } else { if (input.length !== size) { throw new Error('sequentialFill typed array must have the correct length'); } for (var _i = 0; _i < size; _i++) { input[_i] = from; from += step; } } return input; } export { sequentialFill as default };