shift.js (2367B)
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 isArray = require( '@stdlib/assert/is-array' ); 24 var isTypedArrayLike = require( '@stdlib/assert/is-typed-array-like' ); 25 var isInteger = require( '@stdlib/assert/is-integer' ); 26 var shiftObject = require( './shift_object.js' ); 27 var shiftTypedArray = require( './shift_typed_array.js' ); 28 29 30 // MAIN // 31 32 /** 33 * Removes and returns the first element of a collection. 34 * 35 * @param {(Array|TypedArray|Object)} collection - collection 36 * @throws {TypeError} must provide either an array, typed array, or an array-like object 37 * @returns {Array} updated collection and the removed element 38 * 39 * @example 40 * var arr = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]; 41 * 42 * var out = shift( arr ); 43 * // returns [ [ 2.0, 3.0, 4.0, 5.0 ], 1.0 ] 44 * 45 * @example 46 * var Float64Array = require( '@stdlib/array/float64' ); 47 * 48 * var arr = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0 ] ); 49 * // returns <Float64Array>[ 1.0, 2.0, 3.0, 4.0, 5.0 ] 50 * 51 * var out = shift( arr ); 52 * // returns [ <Float64Array>[ 2.0, 3.0, 4.0, 5.0 ], 1.0 ] 53 */ 54 function shift( collection ) { 55 var v; 56 if ( isArray( collection ) ) { 57 v = collection.shift(); 58 return [ collection, v ]; 59 } 60 // Check for a typed-array-like object, as verifying actual typed arrays is expensive... 61 if ( isTypedArrayLike( collection ) ) { 62 return shiftTypedArray( collection ); 63 } 64 // Check for an array-like object... 65 if ( 66 collection !== null && 67 typeof collection === 'object' && 68 typeof collection.length === 'number' && 69 isInteger( collection.length ) && 70 collection.length >= 0 71 ) { 72 return shiftObject( collection ); 73 } 74 throw new TypeError( 'invalid argument. Must provide either an Array, Typed Array, or an array-like Object. Value: `'+collection+'`.' ); 75 } 76 77 78 // EXPORTS // 79 80 module.exports = shift;