piral-core
Version:
The core library for creating a Piral instance.
76 lines • 2.22 kB
JavaScript
// tslint:disable-next-line
export const removeIndicator = null;
// to avoid creating unnecessary empty arrays
export const none = [];
// to avoid creating unnecessary empty functions
export const noop = () => { };
export function prependItem(items, item) {
return [item, ...(items || none)];
}
export function appendItem(items, item) {
return [...(items || none), item];
}
export function prependItems(items, newItems) {
return [...newItems, ...(items || none)];
}
export function appendItems(items, newItems) {
return [...(items || none), ...newItems];
}
export function excludeItem(items, item) {
return (items || none).filter((m) => m !== item);
}
export function includeItem(items, item) {
return appendItem(excludeItem(items, item), item);
}
export function replaceOrAddItem(items, item, predicate) {
const newItems = [...(items || none)];
for (let i = 0; i < newItems.length; i++) {
if (predicate(newItems[i])) {
newItems[i] = item;
return newItems;
}
}
newItems.push(item);
return newItems;
}
export function removeNested(obj, predicate) {
return Object.keys(obj).reduce((entries, key) => {
const item = obj[key];
entries[key] = Object.keys(item).reduce((all, key) => {
const value = item[key];
if (Array.isArray(value)) {
all[key] = excludeOn(value, predicate);
}
else if (!value || !predicate(value)) {
all[key] = value;
}
return all;
}, {});
return entries;
}, {});
}
export function excludeOn(items, predicate) {
return (items || none).filter((m) => !predicate(m));
}
export function updateKey(obj, key, value) {
return value === removeIndicator ? withoutKey(obj, key) : withKey(obj, key, value);
}
export function withKey(obj, key, value) {
return {
...obj,
[key]: value,
};
}
export function withoutKey(obj, key) {
const { [key]: _, ...newObj } = obj || {};
return newObj;
}
export function tryParseJson(content) {
try {
return JSON.parse(content);
}
catch {
return {};
}
}
//# sourceMappingURL=helpers.js.map