Skip to content

Commit ed2469e

Browse files
authored
perf: improve the internal config set function (#5872)
The function is now almost twice as fast and doesn't create any temprary objects in memory.
1 parent 7f44491 commit ed2469e

2 files changed

Lines changed: 12 additions & 12 deletions

File tree

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
'use strict'
22

33
module.exports = function set (object, path, value) {
4-
const pathArr = path.split('.')
5-
let property = object
6-
let i
7-
for (i = 0; i < pathArr.length - 1; i++) {
8-
const n = pathArr[i]
9-
if (property.hasOwnProperty(n)) {
10-
property = property[n]
11-
} else {
12-
property[n] = property = {}
4+
let index = -1
5+
while (true) {
6+
const nextIndex = path.indexOf('.', index + 1)
7+
if (nextIndex === -1) {
8+
object[path.slice(index + 1)] = value
9+
return
1310
}
11+
object = object[path.slice(index + 1, nextIndex)] ??= {}
12+
index = nextIndex
1413
}
15-
property[pathArr[i]] = value
1614
}

packages/datadog-core/test/utils/src/set.spec.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ describe('set', () => {
99
const obj = {}
1010

1111
it('should set value at path', () => {
12-
set(obj, 'a.b', 'c')
13-
expect(obj.a.b).to.be.equal('c')
12+
set(obj, 'a', 1)
13+
set(obj, 'b.c', 2)
14+
set(obj, 'b.d.e', 3)
15+
expect(obj).to.deep.equal({ a: 1, b: { c: 2, d: { e: 3 } } })
1416
})
1517
})

0 commit comments

Comments
 (0)