omit.js (2161B)
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 objectKeys = require( './../../keys' ); 24 var isString = require( '@stdlib/assert/is-string' ).isPrimitive; 25 var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives; 26 var indexOf = require( './../../index-of' ); 27 28 29 // MAIN // 30 31 /** 32 * Returns a partial object copy excluding specified keys. 33 * 34 * @param {Object} obj - source object 35 * @param {(string|StringArray)} keys - keys to exclude 36 * @throws {TypeError} first argument must be an object 37 * @throws {TypeError} second argument must be either a string or an array of strings 38 * @returns {Object} new object 39 * 40 * @example 41 * var obj1 = { 42 * 'a': 1, 43 * 'b': 2 44 * }; 45 * 46 * var obj2 = omit( obj1, 'b' ); 47 * // returns { 'a': 1 } 48 */ 49 function omit( obj, keys ) { 50 var ownKeys; 51 var out; 52 var key; 53 var i; 54 if ( typeof obj !== 'object' || obj === null ) { 55 throw new TypeError( 'invalid argument. First argument must be an object. Value: `'+obj+'`.' ); 56 } 57 ownKeys = objectKeys( obj ); 58 out = {}; 59 if ( isString( keys ) ) { 60 for ( i = 0; i < ownKeys.length; i++ ) { 61 key = ownKeys[ i ]; 62 if ( key !== keys ) { 63 out[ key ] = obj[ key ]; 64 } 65 } 66 return out; 67 } 68 if ( isStringArray( keys ) ) { 69 for ( i = 0; i < ownKeys.length; i++ ) { 70 key = ownKeys[ i ]; 71 if ( indexOf( keys, key ) === -1 ) { 72 out[ key ] = obj[ key ]; 73 } 74 } 75 return out; 76 } 77 throw new TypeError( 'invalid argument. Second argument must be either a string primitive or an array of string primitives. Value: `'+keys+'`.' ); 78 } 79 80 81 // EXPORTS // 82 83 module.exports = omit;