Skip to content

Instantly share code, notes, and snippets.

@NikolaRHristov
Created August 28, 2023 21:55
Show Gist options
  • Save NikolaRHristov/e801c1d98ea83e8ccee5f219a7bd2731 to your computer and use it in GitHub Desktop.
Save NikolaRHristov/e801c1d98ea83e8ccee5f219a7bd2731 to your computer and use it in GitHub Desktop.
/**
* The function converts a nested Map object into a nested plain JavaScript object.
* @param {unknown} Instance - The `Instance` parameter is of type `unknown`, which means it can be any
* type. It is used to represent an instance of a class or an object.
* @returns an object representation of the input `Instance`. If `Instance` is an instance of `Map`,
* the function recursively converts it into an object by iterating over its entries. If an entry value
* is also an instance of `Map`, it is converted recursively as well. The resulting object is then
* returned. If `Instance` is not an instance of `Map`, it is returned as is
*/
export const Put = (Instance: unknown) => {
if (Instance instanceof Map) {
const _Value: {
// rome-ignore lint/suspicious/noExplicitAny:
[key: string]: any;
} = {};
for (const [Key, Value] of Instance.entries()) {
if (Value instanceof Map) {
_Value[Key] = Put(Value);
} else {
_Value[Key] = Value;
}
}
return _Value;
}
return Instance;
};
/**
* The Get function recursively converts an object into a Map data structure.
* @param Instance - The `Instance` parameter is an object that contains key-value pairs. The keys can
* be any string, and the values can be of any type.
* @returns a Map object containing the key-value pairs from the input object.
*/
export const Get = (Instance: {
// rome-ignore lint/suspicious/noExplicitAny:
[key: string]: any;
}) => {
if (typeof Instance === "string") {
return Instance;
}
const _Map = new Map();
if (typeof Instance === "object") {
for (const Key in Instance) {
if (Object.prototype.hasOwnProperty.call(Instance, Key)) {
if (
typeof Instance[Key] === "object" &&
!Array.isArray(Instance[Key])
) {
_Map.set(Key, Get(Instance[Key]));
} else {
_Map.set(Key, Instance[Key]);
}
}
}
}
return _Map;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment