Skip to content

Commit

Permalink
Merge 52e5558 into 4a22045
Browse files Browse the repository at this point in the history
  • Loading branch information
atlas-ssallay committed Apr 6, 2019
2 parents 4a22045 + 52e5558 commit 746bf61
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
7 changes: 5 additions & 2 deletions README.md
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
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
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});
});
});

});

});

0 comments on commit 746bf61

Please sign in to comment.