Skip to content

Commit fa5386b

Browse files
committed
normalize returns new object
1 parent 6b5bda3 commit fa5386b

File tree

2 files changed

+13
-20
lines changed

2 files changed

+13
-20
lines changed

src/bir.ts

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,10 +61,7 @@ export default class Bir {
6161
}
6262

6363
private normalize(obj: any) {
64-
if (this._normalizeFn) {
65-
this._normalizeFn(obj)
66-
}
67-
return obj
64+
return this._normalizeFn ? this._normalizeFn(obj) : obj
6865
}
6966

7067
private async api(options: QueryOptions) {

src/normalize.ts

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ function stripPrefix(name: string, prefix: string | string[]) {
2424
/**
2525
* Replace some strings.
2626
*/
27-
function replace(value: any, replaceArray: [any, any][]) {
27+
function replace(value: string, replaceArray: [string, any][]) {
2828
for (let [search, replace] of replaceArray) {
29-
value = value.replace(search, replace)
29+
if (value === search) value = replace
3030
}
3131
return value
3232
}
@@ -64,28 +64,24 @@ function lowerCamelCase(name: string) {
6464
export function morph(
6565
obj: any,
6666
fn: (key: string, value: any) => { key: string; value: any }
67-
) {
68-
if (typeof obj === 'object') {
67+
): any {
68+
if (typeof obj === 'object' && obj !== null) {
6969
if (Array.isArray(obj)) {
70-
for (const element of obj) {
71-
morph(element, fn)
72-
}
70+
return obj.map((element: any) => morph(element, fn))
7371
} else {
72+
let newObj: Record<string, any> = {}
7473
for (let [key, value] of Object.entries(obj)) {
7574
// technically this should never happen here, but let's be safe
7675
assert(typeof key === 'string', 'Only string keys are supported')
76+
7777
if (typeof value === 'object') {
78-
morph(value, fn)
78+
newObj[key] = morph(value, fn)
7979
} else {
8080
const updated = fn(key, value)
81-
if (updated.key !== key) {
82-
delete obj[key]
83-
obj[updated.key] = updated.value
84-
} else if (updated.value !== value) {
85-
obj[key] = updated.value
86-
}
81+
newObj[updated.key] = updated.value
8782
}
8883
}
84+
return newObj
8985
}
9086
}
9187
}
@@ -104,7 +100,7 @@ export function morph(
104100
* @deprecated
105101
*/
106102
export function legacy(obj: any) {
107-
morph(obj, (key: string, value: any) => {
103+
return morph(obj, (key: string, value: any) => {
108104
key = stripPrefix(key, 'praw_')
109105
key = lowerFirstLetter(key)
110106
value = replace(value, [['', undefined]])
@@ -117,7 +113,7 @@ export function legacy(obj: any) {
117113
* @beta
118114
*/
119115
export function modern(obj: any) {
120-
morph(obj, (key: string, value: any) => {
116+
return morph(obj, (key: string, value: any) => {
121117
key = stripPrefix(key, [
122118
'fiz_',
123119
'praw_',

0 commit comments

Comments
 (0)