-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
60 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
/* -------------------------------------------- | ||
* | ||
* Remove undefined fields from an object | ||
* | ||
* -------------------------------------------- | ||
*/ | ||
export default function filterObject (obj) { | ||
return fromEntries(Object.entries(obj).filter(([key, value]) => { | ||
return value !== undefined; | ||
})); | ||
} | ||
|
||
function fromEntries(iter) { | ||
const obj = {}; | ||
|
||
for (const pair of iter) { | ||
if (Object(pair) !== pair) { | ||
throw new TypeError('iterable for fromEntries should yield objects'); | ||
} | ||
|
||
// Consistency with Map: contract is that entry has "0" and "1" keys, not | ||
// that it is an array or iterable. | ||
|
||
const { '0': key, '1': val } = pair; | ||
|
||
Object.defineProperty(obj, key, { | ||
configurable: true, | ||
enumerable: true, | ||
writable: true, | ||
value: val, | ||
}); | ||
} | ||
|
||
return obj; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/* globals describe it */ | ||
import * as assert from 'assert'; | ||
import filterObject from '../src/utils/filterObject.js'; | ||
|
||
const name = 'filterObject'; | ||
|
||
const tests = [ | ||
{ args: [{}], expected: {} }, | ||
{ args: [{x: null, y: undefined}], expected: { x: null } }, | ||
{ args: [{x: 'a', y: undefined, z: undefined}], expected: { x: 'a' } }, | ||
{ args: [{x: 'a', y: 'b', z: undefined}], expected: { x: 'a', y: 'b' } }, | ||
]; | ||
|
||
describe(name, () => { | ||
tests.forEach(test => { | ||
describe(JSON.stringify(test.args), () => { | ||
it(`should equal ${JSON.stringify(test.expected)}`, () => { | ||
const actual = filterObject(...test.args); | ||
assert.deepStrictEqual(actual, test.expected); | ||
}); | ||
}); | ||
}); | ||
}); |