pick-by-alias
Advanced tools
Comparing version 1.0.0 to 1.1.0
25
index.js
'use strict' | ||
var CACHE = {} | ||
@@ -8,9 +7,15 @@ module.exports = function pick (src, props) { | ||
if (typeof props === 'string') props = toList(props) | ||
if (Array.isArray(props)) { | ||
let res = {} | ||
for (var i = 0; i < props.length; i++) { | ||
res[props[i]] = true | ||
} | ||
props = res | ||
} | ||
for (var prop in props) { | ||
var aliases = props[prop] | ||
if (CACHE[aliases]) aliases = CACHE[aliases] | ||
else if (typeof aliases === 'string') { | ||
aliases = CACHE[aliases] = aliases.split(/\s*,\s*|\s+/) | ||
} | ||
aliases = toList(aliases) | ||
@@ -34,1 +39,11 @@ if (Array.isArray(aliases)) { | ||
} | ||
var CACHE = {} | ||
function toList(arg) { | ||
if (CACHE[arg]) return CACHE[arg] | ||
if (typeof arg === 'string') { | ||
arg = CACHE[arg] = arg.split(/\s*,\s*|\s+/) | ||
} | ||
return arg | ||
} |
{ | ||
"name": "pick-by-alias", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "Pick properties by aliases", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -26,6 +26,21 @@ # pick-by-alias [](http://github.com/badges/stability-badges) | ||
Return an object consisting of the properties picked by the list of aliases. The aliases are matched in priority order, ie. the names going first are picked. Each alias can be an array or a comma/space-separated string. | ||
Return an object with properties picked by the list or dict of `aliases`. The `aliases` are matched in priority order, ie. the names going first are picked. Each alias can be an array or a comma/space-separated string. | ||
```js | ||
// pick by dict | ||
let {a, b} = pick(src, {a: ['a', 'b', 'c'], b: 'd e f'}) | ||
// pick by list | ||
let {c, d, e} = pick(src, ['c', 'd', 'e']) | ||
// pick by string | ||
let {f, g} = pick(src, 'f g') | ||
``` | ||
## Related | ||
* [defined](https://www.npmjs.com/package/defined) − get first non-undefined out of a list of values | ||
## License | ||
(c) 2017 Dima Yv. MIT License |
27
test.js
@@ -6,3 +6,3 @@ 'use strict' | ||
t('default', t => { | ||
t('obj', t => { | ||
let res = pick({ | ||
@@ -27,1 +27,26 @@ a: 0, | ||
}) | ||
t('array', t => { | ||
t.deepEqual(pick({ | ||
a: 0, | ||
b: null, | ||
c: undefined, | ||
d: 1, | ||
e: [0, 1] | ||
}, ['a', 'b', 'c', 'd']), {a: 0, b: null, c: undefined, d: 1}) | ||
t.end() | ||
}) | ||
t('string', t => { | ||
t.deepEqual(pick({ | ||
a: 0, | ||
b: null, | ||
c: undefined, | ||
d: 1, | ||
e: [0, 1] | ||
}, 'a b c d'), {a: 0, b: null, c: undefined, d: 1}) | ||
t.end() | ||
}) |
4708
121
46