@voiceflow/common
Version:
Junk drawer of utility functions
70 lines (69 loc) • 2.03 kB
JavaScript
import { isPlainObject } from './common.js';
export const deepMap = (object, mapFunction, options = {}) => {
const cache = new WeakMap();
const mapArray = (arr) => {
if (cache.has(arr)) {
return cache.get(arr);
}
const result = options.inPlace ? arr : [];
cache.set(arr, result);
const { length } = arr;
for (let index = 0; index < length; index++) {
result[index] = map(arr[index], index);
}
return result;
};
const mapObject = (obj) => {
if (cache.has(obj)) {
return cache.get(obj);
}
const result = options.inPlace ? obj : {};
cache.set(obj, result);
for (const key of Object.keys(obj)) {
result[key] = map(obj[key], key);
}
return result;
};
const map = (value, key) => {
if (Array.isArray(value))
return mapArray(value);
if (isPlainObject(value))
return mapObject(value);
return mapFunction(value, key);
};
return map(object);
};
export const deepMapKeys = (object, mapFunction) => {
const cache = new WeakMap();
const mapArray = (arr) => {
if (cache.has(arr)) {
return cache.get(arr);
}
const result = [];
cache.set(arr, result);
const { length } = arr;
for (let i = 0; i < length; i++) {
result.push(map(arr[i]));
}
return result;
};
const mapObject = (obj) => {
if (cache.has(obj)) {
return cache.get(obj);
}
const result = {};
cache.set(obj, result);
for (const key of Object.keys(obj)) {
result[mapFunction(key, obj[key])] = map(obj[key]);
}
return result;
};
const map = (value) => {
if (Array.isArray(value))
return mapArray(value);
if (isPlainObject(value))
return mapObject(value);
return value;
};
return map(object);
};