forked from OKEAMAH/js-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject.ts
More file actions
48 lines (45 loc) · 1.85 KB
/
object.ts
File metadata and controls
48 lines (45 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Merges two objects together, prioritizing the properties of the second object.
* If a property exists in both objects, the value from the second object will be used.
* @param credSubject - The first object to merge.
* @param otherCredSubject - The second object to merge.
* @returns A new object with the merged properties.
*/
type obj = { [k: string]: unknown };
export function mergeObjects(credSubject: obj, otherCredSubject: obj) {
let result = {} as obj;
const credSubjectKeys = Object.keys(credSubject);
for (const key of credSubjectKeys) {
if (typeof otherCredSubject[key] !== 'undefined') {
if (typeof credSubject[key] !== 'object' && typeof otherCredSubject[key] !== 'object') {
throw new Error('Invalid query');
}
const subjectProperty = credSubject[key] as obj;
const otherSubjectProperty = otherCredSubject[key] as obj;
const propertyOperators = Object.keys(subjectProperty);
const subjectPropertyResult: obj = {};
for (const operatorKey of propertyOperators) {
if (typeof otherSubjectProperty[operatorKey] !== 'undefined') {
const operatorValue1 = subjectProperty[operatorKey] as obj;
const operatorValue2 = otherSubjectProperty[operatorKey];
subjectPropertyResult[operatorKey] = [
...new Set([
...((subjectPropertyResult[operatorKey] as Array<obj>) ?? []),
operatorValue1,
...(Array.isArray(operatorValue2) ? operatorValue2 : [operatorValue2])
])
];
} else {
subjectPropertyResult[operatorKey] = subjectProperty[operatorKey];
}
}
result[key] = {
...(otherCredSubject[key] as obj),
...subjectPropertyResult
};
}
}
// Add remaining keys from obj2
result = { ...credSubject, ...otherCredSubject, ...result };
return result;
}