/**
* @module objects
* @description This module contains routines for objects manipulation
*/
'use strict';
import {getRandomInt} from './numbers.js';
export function clone(object) {
let
objectString,
result;
try {
if (object) {
objectString = JSON.stringify(object);
result = JSON.parse(objectString);
}
} catch (error) { }
return result;
}
export function resolvePath(object, path, defaultValue) {
return path
.split('.')
.reduce(
async (o, p) => {
let result;
if (o instanceof Promise)
o = await o;
result = o ? o[p] : defaultValue;
return result;
},
object
);
}
export function objectToPath(obj, path = '') {
let result = '';
for (let key in obj) {
if (typeof obj[key] === 'object' && obj[key] !== null) {
result += objectToPath(obj[key], path + key + '.');
} else
result += path + key + '.';
}
return result.slice(0, -1);
}
export function setValueByPath(obj, path, value) {
const parts = path.split('.');
let current = obj;
for (let i = 0; i < parts.length; i++) {
if (
typeof current !== 'undefined' &&
typeof parts[i] !== 'undefined'
)
if (i === parts.length - 1)
current[parts[i]] = value
else
current = current[parts[i]];
}
}
export function getValueByPath(obj, path) {
const
parts = path.split('.');
let
result,
current = obj;
for (let i = 0; i < parts.length; i++) {
if (
typeof current !== 'undefined' &&
typeof parts[i] !== 'undefined'
)
if (i === parts.length - 1) {
result = current[parts[i]]
} else
current = current[parts[i]];
}
return result;
}
/**
* This is a function to retrieve a random value from a list of key-value
* pairs, where the keys satisfy a given regular expression
* @param {string} pattern - A regular expression
* @param {object} list - A list of key-value pairs
* @example
* let
* strings = {
* HELLO_1: 'Привет!',
* HELLO_2: 'Hi',
* HELLO_3: 'Салам!',
* HELLO_4: 'Guten Tag!',
* HELLO_5: 'Hola!'
* },
* pattern = 'HELLO_\\d',
* result;
*
* result = getRandomValue(pattern, strings);
*
* console.log(result); // value of random strings list's item (for example - 'Hi')
* @returns {*} random value
*/
export function getRandomValue(pattern, list) {
let
result,
matchedKeys = [];
for (let key in list)
if (key.match(pattern)) matchedKeys.push(list[key]);
if (matchedKeys.length > 0)
result = matchedKeys[getRandomInt(0, matchedKeys.length - 1)];
return result;
}