Skip to content

Commit 65cd392

Browse files
authored
Merge pull request #51 from ferflores507/dev
Dev
2 parents 56bf670 + 473e0e8 commit 65cd392

File tree

6 files changed

+528
-2
lines changed

6 files changed

+528
-2
lines changed

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
node_modules
1+
node_modules
2+
*.local

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@ferflores507/object-builder",
3-
"version": "9.1.0",
3+
"version": "9.2.0",
44
"main": "index.js",
55
"scripts": {
66
"test": "vitest"

src/builders/Operators.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,55 @@ export class Operators implements WithTaskOptions<Operators> {
169169
trim = (value: string) => value.trim()
170170
removeAccents = removeAccents
171171
stringify = (value: any) => JSON.stringify(value)
172+
mergeByKeys = (arrays: [any, any], keys?: [string, string] | true) => {
173+
174+
arrays = this.values(arrays) as [any, any]
175+
176+
const validateOrThrow = (operator: string, items: any[]) => {
177+
const firstInvalid = items.find(item => !item.isValid)
178+
179+
if(firstInvalid) {
180+
throw {
181+
operator,
182+
...firstInvalid
183+
}
184+
}
185+
}
186+
187+
validateOrThrow("Merge by keys", [
188+
{
189+
isValid: arrays.length === 2,
190+
msg: "Expected an array of 2 elements.",
191+
value: arrays
192+
},
193+
{
194+
isValid: keys,
195+
msg: "Expected a 'true' value for keys.",
196+
value: keys,
197+
}
198+
])
199+
200+
const [array1, array2] = arrays
201+
const concreteKeys = Array.isArray(keys)
202+
? keys
203+
: [1, 2].map(_ => typeof keys == "string" ? keys : "id")
204+
205+
if (concreteKeys.length !== 2) {
206+
throw {
207+
operator: "Merge by keys",
208+
msg: "Expected 2 keys.",
209+
value: concreteKeys
210+
}
211+
}
212+
213+
const map = new Map()
214+
const [key1, key2] = concreteKeys
215+
216+
array1.forEach((item: any) => map.set(item[key1], item))
217+
array2.forEach((item: any) => map.set(item[key2], {...map.get(item[key2]), ...item}))
218+
219+
return Array.from(map.values());
220+
}
172221
sort = (array: any[], option: true | "descending" = true) => {
173222
return this.sortBy(array, { descending: option === "descending" })
174223
}

src/models.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ export type Schema = Partial<{
125125
join: SchemaDefinition | SchemaPrimitive
126126
keywords: true
127127
log: SchemaDefinition | SchemaPrimitive
128+
mergeByKeys: SchemaDefinition | SchemaPrimitive
128129
not: SchemaDefinition
129130
or: SchemaDefinition | SchemaPrimitive
130131
path: string

0 commit comments

Comments
 (0)