@js-data-tools/js-helpers
Version:
A set of JavaScript / TypeScript helper functions for parsing, converting, transforming and formatting data.
45 lines (44 loc) • 1.43 kB
JavaScript
import { isDefaultValue, isEmptyValue } from "../predicates";
export function ignoreEmpty(key, value) {
return isEmptyValue(value) ? undefined : value;
}
export function ignoreDefaults(key, value) {
return isDefaultValue(value) ? undefined : value;
}
export function orderNames(names, options) {
const remained = new Set(names);
const head = [];
const tail = [];
if (options.first?.length) {
head.push(...options.first.filter((name) => remained.delete(name)));
}
if (options.last?.length) {
tail.push(...options.last.filter((name) => remained.delete(name)));
}
if (options.sort) {
const body = [...remained.values()].sort();
if (options.sortDescending) {
body.reverse();
}
return [...head, ...body, ...tail];
}
return [...head, ...remained.values(), ...tail];
}
export function reorderProperties(source, options, inplace) {
if (!options.first?.length && !options.last?.length && !options.sort) {
return inplace !== false ? source : Object.assign({}, source);
}
const keys = Object.keys(source);
const ordered = orderNames(keys, options);
const target = {};
for (const name of ordered) {
target[name] = source[name];
if (inplace) {
delete source[name];
}
}
if (inplace) {
return Object.assign(source, target);
}
return target;
}