UNPKG

@aricma/itemids

Version:

Be faster in creating and updating react state, with the ItemIds object.

72 lines (60 loc) 2.46 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.isItemIds = isItemIds; exports.isItemId = isItemId; exports.isItemIdList = isItemIdList; exports.unify = unify; var ERRORS = _interopRequireWildcard(require("../errors")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } /** * the itemIds static methods */ /** * @param {*} [object] * @return {boolean} */ function isItemIds(object) { let isItemIds = false; const gotArray = Array.isArray(object); const hasItemIdsName = !!gotArray && object.name === "ItemIds"; if (hasItemIdsName) isItemIds = true; return isItemIds; } /** * @param {*} [value] * @return {boolean} */ function isItemId(value) { const isString = typeof value === "string"; const isNumber = typeof value === "number" && !Number.isNaN(value); return isString || isNumber; } /** * @param {*} [value] * @return {boolean} */ function isItemIdList(value) { const isNoArray = !Array.isArray(value); if (isNoArray) return false; return value.reduce((state, value) => state && isItemId(value), true); } /** * remove all duplicates * is not mutating * @param {*} object * @return {Array} - the given object */ function unify(object = []) { const gotNoItemIdList = !isItemIdList(object); if (gotNoItemIdList) throw Error(ERRORS.staticMethods.unify.gotNoItemIdList); const values = object.splice(0); values.reduce((object, itemId) => { const isNoDuplicate = !object.includes(itemId); if (isNoDuplicate) object.push(itemId); return object; }, object); return object; }