UNPKG

@js-data-tools/js-helpers

Version:

A set of JavaScript / TypeScript helper functions for parsing, converting, transforming and formatting data.

52 lines (51 loc) 1.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.reorderProperties = exports.orderNames = exports.ignoreDefaults = exports.ignoreEmpty = void 0; const predicates_1 = require("../predicates"); function ignoreEmpty(key, value) { return (0, predicates_1.isEmptyValue)(value) ? undefined : value; } exports.ignoreEmpty = ignoreEmpty; function ignoreDefaults(key, value) { return (0, predicates_1.isDefaultValue)(value) ? undefined : value; } exports.ignoreDefaults = ignoreDefaults; 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]; } exports.orderNames = orderNames; 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; } exports.reorderProperties = reorderProperties;