You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
1.3 KiB
78 lines
1.3 KiB
4 years ago
|
'use strict'
|
||
|
|
||
|
|
||
|
module.exports = function pick (src, props, keepRest) {
|
||
|
var result = {}, prop, i
|
||
|
|
||
|
if (typeof props === 'string') props = toList(props)
|
||
|
if (Array.isArray(props)) {
|
||
|
var res = {}
|
||
|
for (i = 0; i < props.length; i++) {
|
||
|
res[props[i]] = true
|
||
|
}
|
||
|
props = res
|
||
|
}
|
||
|
|
||
|
// convert strings to lists
|
||
|
for (prop in props) {
|
||
|
props[prop] = toList(props[prop])
|
||
|
}
|
||
|
|
||
|
// keep-rest strategy requires unmatched props to be preserved
|
||
|
var occupied = {}
|
||
|
|
||
|
for (prop in props) {
|
||
|
var aliases = props[prop]
|
||
|
|
||
|
if (Array.isArray(aliases)) {
|
||
|
for (i = 0; i < aliases.length; i++) {
|
||
|
var alias = aliases[i]
|
||
|
|
||
|
if (keepRest) {
|
||
|
occupied[alias] = true
|
||
|
}
|
||
|
|
||
|
if (alias in src) {
|
||
|
result[prop] = src[alias]
|
||
|
|
||
|
if (keepRest) {
|
||
|
for (var j = i; j < aliases.length; j++) {
|
||
|
occupied[aliases[j]] = true
|
||
|
}
|
||
|
}
|
||
|
|
||
|
break
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
else if (prop in src) {
|
||
|
if (props[prop]) {
|
||
|
result[prop] = src[prop]
|
||
|
}
|
||
|
|
||
|
if (keepRest) {
|
||
|
occupied[prop] = true
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (keepRest) {
|
||
|
for (prop in src) {
|
||
|
if (occupied[prop]) continue
|
||
|
result[prop] = src[prop]
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return result
|
||
|
}
|
||
|
|
||
|
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
|
||
|
}
|