Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
the keys of any nested objects – according to some function. Circular
references are supported.

To transform the *values* of an object rather than its keys, use
To transform the _values_ of an object rather than its keys, use
[Deep Map][deep-map].

## Install
Expand Down Expand Up @@ -122,6 +122,9 @@ And the result will look like this:
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a>
within <code>mapFn()</code>
</li>
<li>
<strong>shouldTransformFn</strong> &lt;<code>function</code>&gt; Function used to customize whether a value in the object should be deeply/recursively mapped. The function receives a key and a value and must output a boolean.
</li>
</ul>
</td>
</tr>
Expand All @@ -145,7 +148,7 @@ interface Result {
userName: string;
}

let result = deepMapKeys<Result>({user_name: 'Pumbaa'}, snakeToCamel);
let result = deepMapKeys<Result>({ user_name: 'Pumbaa' }, snakeToCamel);

let name = result.userName; // Everything is OK :)
```
Expand Down
8 changes: 6 additions & 2 deletions src/deep-map-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface MapFn {

export interface Opts {
thisArg?: any;
shouldTransformFn?: (key?: string, value?: any) => boolean;
}

export class DeepMapKeys {
Expand Down Expand Up @@ -50,13 +51,16 @@ export class DeepMapKeys {
return this.cache.get(obj);
}

let {mapFn, opts: {thisArg}} = this;
let {mapFn, opts: {thisArg, shouldTransformFn}} = this;
let result: NonPrimitive = {};
this.cache.set(obj, result);

for (let key in obj) {
if (obj.hasOwnProperty(key)) {
result[mapFn.call(thisArg, key, obj[key])] = this.map(obj[key]);
result[mapFn.call(thisArg, key, obj[key])] =
(!shouldTransformFn || shouldTransformFn(key, obj[key])) ?
this.map(obj[key]) :
obj[key];
}
}

Expand Down
11 changes: 11 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,17 @@ describe('deepMapKeys(object, mapFn, [options])', () => {

});

describe('option: shouldTransformFn', () => {
it('prevents mapping through values for which @shouldTransformFn returns false', () => {
let shouldTransformFn = sinon.spy((key: string, value: any) => key !== 'noTransform');
let obj = {one: 1, noTransform: {two: 2}};

deepMapKeys(obj, caps, {shouldTransformFn}).should.deep.equal({ONE: 1, NOTRANSFORM: {two: 2}});
shouldTransformFn.should.have.been.calledWith('one', 1);
shouldTransformFn.should.have.been.calledWith('noTransform', {two: 2});
});
});

});

});