2021-04-20 21:06:27 +02:00
|
|
|
export const generateID = () => {
|
2021-05-03 09:31:09 +02:00
|
|
|
const rand = Math.random().toString(32).substring(2)
|
2021-04-20 21:06:27 +02:00
|
|
|
|
|
|
|
// Starts with a letter so that its a valid DOM ID
|
|
|
|
return `A${rand}`
|
|
|
|
}
|
2021-06-23 12:47:07 +02:00
|
|
|
|
|
|
|
export const capitalise = s => s.substring(0, 1).toUpperCase() + s.substring(1)
|
2021-12-06 13:37:50 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Gets a key within an object. The key supports dot syntax for retrieving deep
|
|
|
|
* fields - e.g. "a.b.c".
|
|
|
|
* Exact matches of keys with dots in them take precedence over nested keys of
|
|
|
|
* the same path - e.g. getting "a.b" from { "a.b": "foo", a: { b: "bar" } }
|
|
|
|
* will return "foo" over "bar".
|
|
|
|
* @param obj the object
|
|
|
|
* @param key the key
|
2021-12-10 15:18:01 +01:00
|
|
|
* @return {*|null} the value or null if a value was not found for this key
|
2021-12-06 13:37:50 +01:00
|
|
|
*/
|
|
|
|
export const deepGet = (obj, key) => {
|
|
|
|
if (!obj || !key) {
|
|
|
|
return null
|
|
|
|
}
|
2021-12-10 15:18:01 +01:00
|
|
|
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
2021-12-06 13:37:50 +01:00
|
|
|
return obj[key]
|
|
|
|
}
|
|
|
|
const split = key.split(".")
|
|
|
|
for (let i = 0; i < split.length; i++) {
|
2021-12-10 15:18:01 +01:00
|
|
|
obj = obj?.[split[i]]
|
2021-12-06 13:37:50 +01:00
|
|
|
}
|
2021-12-10 15:18:01 +01:00
|
|
|
return obj
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Sets a key within an object. The key supports dot syntax for retrieving deep
|
|
|
|
* fields - e.g. "a.b.c".
|
|
|
|
* Exact matches of keys with dots in them take precedence over nested keys of
|
|
|
|
* the same path - e.g. setting "a.b" of { "a.b": "foo", a: { b: "bar" } }
|
|
|
|
* will override the value "foo" rather than "bar".
|
2021-12-10 16:27:04 +01:00
|
|
|
* If a deep path is specified and the parent keys don't exist then these will
|
|
|
|
* be created.
|
2021-12-10 15:18:01 +01:00
|
|
|
* @param obj the object
|
|
|
|
* @param key the key
|
|
|
|
* @param value the value
|
|
|
|
*/
|
|
|
|
export const deepSet = (obj, key, value) => {
|
|
|
|
if (!obj || !key) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
|
|
obj[key] = value
|
|
|
|
return
|
|
|
|
}
|
|
|
|
const split = key.split(".")
|
|
|
|
for (let i = 0; i < split.length - 1; i++) {
|
2021-12-10 16:27:04 +01:00
|
|
|
const nextKey = split[i]
|
|
|
|
if (obj && obj[nextKey] == null) {
|
|
|
|
obj[nextKey] = {}
|
|
|
|
}
|
|
|
|
obj = obj?.[nextKey]
|
|
|
|
}
|
|
|
|
if (!obj) {
|
|
|
|
return
|
2021-12-10 15:18:01 +01:00
|
|
|
}
|
|
|
|
obj[split[split.length - 1]] = value
|
2021-12-06 13:37:50 +01:00
|
|
|
}
|