From e890cf5bb1ca69790c5f0f8c05d4969c5222593f Mon Sep 17 00:00:00 2001 From: Brett Sun Date: Mon, 2 Nov 2015 18:31:01 +0100 Subject: [PATCH] Cherry pick changes to excludePropFromObject() --- js/utils/general_utils.js | 39 +++++++++++++++++++++++++++++++++------ js/utils/requests.js | 8 ++++---- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/js/utils/general_utils.js b/js/utils/general_utils.js index 7c13f9b5..d60b91fa 100644 --- a/js/utils/general_utils.js +++ b/js/utils/general_utils.js @@ -196,14 +196,41 @@ export function escapeHTML(s) { return document.createElement('div').appendChild(document.createTextNode(s)).parentNode.innerHTML; } -export function excludePropFromObject(obj, propList){ - let clonedObj = mergeOptions({}, obj); - for (let item in propList){ - if (clonedObj[propList[item]]){ - delete clonedObj[propList[item]]; +/** + * Returns a copy of the given object's own and inherited enumerable + * properties, omitting any keys that pass the given filter function. + */ +function filterObjOnFn(obj, filterFn) { + const filteredObj = {}; + + for (let key in obj) { + const val = obj[key]; + if (filterFn == null || !filterFn(val, key)) { + filteredObj[key] = val; } } - return clonedObj; + + return filteredObj; +} + +/** + * Similar to lodash's _.omit(), this returns a copy of the given object's + * own and inherited enumerable properties, omitting any keys that are + * in the given array or whose value pass the given filter function. + * @param {object} obj Source object + * @param {array|function} filter Array of key names to omit or function to invoke per iteration + * @return {object} The new object +*/ +export function omitFromObject(obj, filter) { + if (filter && filter.constructor === Array) { + return filterObjOnFn(obj, (_, key) => { + return filter.indexOf(key) >= 0; + }); + } else if (filter && typeof filter === 'function') { + return filterObjOnFn(obj, filter); + } else { + throw new Error('The given filter is not an array or function. Exclude aborted'); + } } /** diff --git a/js/utils/requests.js b/js/utils/requests.js index 7e9c9a58..43c09458 100644 --- a/js/utils/requests.js +++ b/js/utils/requests.js @@ -6,7 +6,7 @@ import { argsToQueryParams, getCookie } from '../utils/fetch_api_utils'; import AppConstants from '../constants/application_constants'; -import {excludePropFromObject} from '../utils/general_utils'; +import { omitFromObject } from '../utils/general_utils'; class Requests { _merge(defaults, options) { @@ -138,9 +138,9 @@ class Requests { return this.request('delete', newUrl); } - _putOrPost(url, paramsAndBody, method){ - let paramsCopy = this._merge(paramsAndBody); - let params = excludePropFromObject(paramsAndBody, ['body']); + _putOrPost(url, paramsAndBody, method) { + let paramsCopy = Object.assign({}, paramsAndBody); + let params = omitFromObject(paramsAndBody, ['body']); let newUrl = this.prepareUrl(url, params); let body = null; if (paramsCopy && paramsCopy.body) {