Skip to content

Commit 4eee017

Browse files
authored
feat(inspect): add deepMap function (#35)
* feat(inspect): add deepMap function * test: adding deepMap test case * docs: clarification of func(item) * fix: s/deep/deepMap * refactor: call func late
1 parent 1199b50 commit 4eee017

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

docs/inspect.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,23 @@ local inspect = import "github.com/jsonnet-libs/xtd/inspect.libsonnet"
1212

1313
## Index
1414

15+
* [`fn deepMap(func, x)`](#fn-deepmap)
1516
* [`fn diff(input1, input2)`](#fn-diff)
1617
* [`fn filterKubernetesObjects(object, kind='')`](#fn-filterkubernetesobjects)
1718
* [`fn filterObjects(filter_func, x)`](#fn-filterobjects)
1819
* [`fn inspect(object, maxDepth)`](#fn-inspect)
1920

2021
## Fields
2122

23+
### fn deepMap
24+
25+
```ts
26+
deepMap(func, x)
27+
```
28+
29+
`deepMap` traverses the whole tree of `x` and applies `func(item)` indiscriminately.
30+
31+
2232
### fn diff
2333

2434
```ts

inspect.libsonnet

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,4 +206,22 @@ local d = import 'github.com/jsonnet-libs/docsonnet/doc-util/main.libsonnet';
206206
function(o) o.kind == kind,
207207
objects
208208
),
209+
210+
'#deepMap':: d.fn(
211+
|||
212+
`deepMap` traverses the whole tree of `x` and applies `func(item)` indiscriminately.
213+
|||,
214+
args=[
215+
d.arg('func', d.T.func),
216+
d.arg('x', d.T.any),
217+
]
218+
),
219+
deepMap(func, x):
220+
func(
221+
if std.isObject(x)
222+
then std.mapWithKey(function(_, y) self.deepMap(func, y), x)
223+
else if std.isArray(x)
224+
then std.map(function(y) self.deepMap(func, y), x)
225+
else x
226+
),
209227
}

test/inspect_test.jsonnet

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,3 +150,42 @@ test.new(std.thisFile)
150150
)
151151
)
152152
)
153+
+ (
154+
local originalObj = {
155+
key1: {
156+
key1a: 'replace me',
157+
key1b: [
158+
{ key1bNested: 'replace me' },
159+
],
160+
},
161+
key2: [
162+
{ key2a: 'replace me' },
163+
],
164+
};
165+
166+
test.case.new(
167+
name='deepmap',
168+
test=
169+
test.expect.eq(
170+
actual=xtd.inspect.deepMap(
171+
function(item)
172+
if std.isString(item)
173+
&& item == 'replace me'
174+
then 'REPLACED'
175+
else item,
176+
originalObj,
177+
),
178+
expected={
179+
key1: {
180+
key1a: 'REPLACED',
181+
key1b: [
182+
{ key1bNested: 'REPLACED' },
183+
],
184+
},
185+
key2: [
186+
{ key2a: 'REPLACED' },
187+
],
188+
}
189+
)
190+
)
191+
)

0 commit comments

Comments
 (0)