From ce64147aa8348dde3bd2479824c6624108ce98ff Mon Sep 17 00:00:00 2001 From: Tom Najdek Date: Mon, 6 Nov 2023 11:34:56 +0100 Subject: [PATCH] Add "pick" and "omit" utils Helpful when dealing with props in react components --- chrome/content/zotero/components/utils.js | 48 ++++++++++++++++++++++- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/chrome/content/zotero/components/utils.js b/chrome/content/zotero/components/utils.js index ebe4969b67..00ae5d3c08 100644 --- a/chrome/content/zotero/components/utils.js +++ b/chrome/content/zotero/components/utils.js @@ -95,6 +95,50 @@ const scrollIntoViewIfNeeded = (element, container, opts = {}) => { const stopPropagation = ev => ev.stopPropagation(); -export { - nextHTMLID, noop, getDragTargetOrient, createDragHandler, scrollIntoViewIfNeeded, stopPropagation +// pick and omit from https://github.com/zotero/web-common/blob/master/utils/immutable.js +const omit = (object, deleteKeys) => { + if (typeof (deleteKeys) !== 'function') { + if (!Array.isArray(deleteKeys)) { + deleteKeys = [deleteKeys]; + } + deleteKeys = deleteKeys.map(dk => (typeof (dk) !== 'string' ? dk.toString() : dk)); + } + + return Object.entries(object) + .reduce((aggr, [key, value]) => { + if (typeof (deleteKeys) === 'function') { + if (!deleteKeys(key, value)) { aggr[key] = value; } + } else if (!deleteKeys.includes(key)) { + aggr[key] = value; + } + return aggr; + }, {}); +}; + +const pick = (object, pickKeys) => { + if (typeof (pickKeys) === 'function') { + return Object.entries(object) + .reduce((aggr, [key, value]) => { + if (pickKeys(key)) { + aggr[key] = value; + } + return aggr; + }, {}); + } + if (!Array.isArray(pickKeys)) { + pickKeys = [pickKeys]; + } + + return Object.entries(object) + .reduce((aggr, [key, value]) => { + if (pickKeys.includes(key)) { + aggr[key] = value; + } + return aggr; + }, {}); +}; + + +export { + nextHTMLID, noop, getDragTargetOrient, createDragHandler, scrollIntoViewIfNeeded, stopPropagation, pick, omit };