@difizen/mana-common
Version:
246 lines (242 loc) • 8.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.cloneAndChange = cloneAndChange;
exports.deepClone = deepClone;
exports.deepFreeze = deepFreeze;
exports.distinct = distinct;
exports.getCaseInsensitive = getCaseInsensitive;
exports.getOrDefault = getOrDefault;
exports.isEmpty = isEmpty;
exports.mixin = mixin;
exports.notEmpty = notEmpty;
exports.objectEquals = objectEquals;
exports.safeStringify = safeStringify;
var _valueTypes = require("./valueTypes");
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
function deepClone(obj) {
if (!obj || _typeof(obj) !== 'object') {
return obj;
}
if (obj instanceof RegExp) {
// See https://github.com/microsoft/TypeScript/issues/10990
return obj;
}
var result = Array.isArray(obj) ? [] : {};
Object.keys(obj).forEach(function (key) {
if (obj[key] && _typeof(obj[key]) === 'object') {
result[key] = deepClone(obj[key]);
} else {
result[key] = obj[key];
}
});
return result;
}
function deepFreeze(obj) {
if (!obj || _typeof(obj) !== 'object') {
return obj;
}
var stack = [obj];
while (stack.length > 0) {
var _obj = stack.shift();
Object.freeze(_obj);
for (var key in _obj) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
if (_hasOwnProperty.call(_obj, key)) {
var prop = _obj[key];
if (_typeof(prop) === 'object' && !Object.isFrozen(prop)) {
stack.push(prop);
}
}
}
}
return obj;
}
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function cloneAndChange(obj, changer) {
return _cloneAndChange(obj, changer, new Set());
}
function _cloneAndChange(obj, changer, seen) {
if ((0, _valueTypes.isUndefinedOrNull)(obj)) {
return obj;
}
var changed = changer(obj);
if (typeof changed !== 'undefined') {
return changed;
}
if ((0, _valueTypes.isArray)(obj)) {
var r1 = [];
var _iterator = _createForOfIteratorHelper(obj),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var e = _step.value;
r1.push(_cloneAndChange(e, changer, seen));
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
return r1;
}
if ((0, _valueTypes.isObject)(obj)) {
if (seen.has(obj)) {
throw new Error('Cannot clone recursive data-structure');
}
seen.add(obj);
var r2 = {};
for (var i2 in obj) {
if (_hasOwnProperty.call(obj, i2)) {
r2[i2] = _cloneAndChange(obj[i2], changer, seen);
}
}
seen.delete(obj);
return r2;
}
return obj;
}
/**
* Copies all properties of source into destination. The optional parameter "overwrite" allows to control
* if existing properties on the destination should be overwritten or not. Defaults to true (overwrite).
*/
function mixin(destination, source) {
var overwrite = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
if (!(0, _valueTypes.isObject)(destination)) {
return source;
}
if ((0, _valueTypes.isObject)(source)) {
Object.keys(source).forEach(function (key) {
if (key in destination) {
if (overwrite) {
if ((0, _valueTypes.isObject)(destination[key]) && (0, _valueTypes.isObject)(source[key])) {
mixin(destination[key], source[key], overwrite);
} else {
destination[key] = source[key];
}
}
} else {
destination[key] = source[key];
}
});
}
return destination;
}
function objectEquals(one, other) {
if (one === other) {
return true;
}
if (one === null || one === undefined || other === null || other === undefined) {
return false;
}
if (_typeof(one) !== _typeof(other)) {
return false;
}
if (_typeof(one) !== 'object') {
return false;
}
if (Array.isArray(one) !== Array.isArray(other)) {
return false;
}
var i;
var key;
if (Array.isArray(one)) {
if (one.length !== other.length) {
return false;
}
for (i = 0; i < one.length; i++) {
if (!objectEquals(one[i], other[i])) {
return false;
}
}
} else {
var oneKeys = [];
for (key in one) {
oneKeys.push(key);
}
oneKeys.sort();
var otherKeys = [];
for (key in other) {
otherKeys.push(key);
}
otherKeys.sort();
if (!objectEquals(oneKeys, otherKeys)) {
return false;
}
for (i = 0; i < oneKeys.length; i++) {
if (!objectEquals(one[oneKeys[i]], other[oneKeys[i]])) {
return false;
}
}
}
return true;
}
/**
* Calls `JSON.Stringify` with a replacer to break apart any circular references.
* This prevents `JSON`.stringify` from throwing the exception
* "Uncaught TypeError: Converting circular structure to JSON"
*/
function safeStringify(obj) {
var seen = new Set();
return JSON.stringify(obj, function (_key, value) {
if ((0, _valueTypes.isObject)(value) || Array.isArray(value)) {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
}
return value;
});
}
function getOrDefault(obj, fn, defaultValue) {
var result = fn(obj);
return typeof result === 'undefined' ? defaultValue : result;
}
/**
* Returns an object that has keys for each value that is different in the base object. Keys
* that do not exist in the target but in the base object are not considered.
*
* Note: This is not a deep-diffing method, so the values are strictly taken into the resulting
* object if they differ.
*
* @param base the object to diff against
* @param obj the object to use for diffing
*/
function distinct(base, target) {
var result = Object.create(null);
if (!base || !target) {
return result;
}
var targetKeys = Object.keys(target);
targetKeys.forEach(function (k) {
var baseValue = base[k];
var targetValue = target[k];
if (!objectEquals(baseValue, targetValue)) {
result[k] = targetValue;
}
});
return result;
}
function getCaseInsensitive(target, key) {
var lowercaseKey = key.toLowerCase();
var equivalentKey = Object.keys(target).find(function (k) {
return k.toLowerCase() === lowercaseKey;
});
return equivalentKey ? target[equivalentKey] : target[key];
}
function notEmpty(arg) {
return arg !== undefined && arg !== null;
}
/**
* `true` if the argument is an empty object. Otherwise, `false`.
*/
function isEmpty(arg) {
return Object.keys(arg).length === 0 && arg.constructor === Object;
}