-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathkeyPath.js
More file actions
37 lines (33 loc) · 811 Bytes
/
keyPath.js
File metadata and controls
37 lines (33 loc) · 811 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* @copyright 2015, Prometheus Research, LLC
*/
import isString from 'lodash/isString';
import isArray from 'lodash/isArray';
import invariant from 'invariant';
const IS_NUMBER = /^[0-9]+$/;
function tryParseInt(v) {
if (typeof v === 'string' && IS_NUMBER.exec(v)) {
v = parseInt(v, 10);
}
return v;
}
export default function keyPath(value) {
if (isArray(value)) {
return value;
} else if (isString(value)) {
if (value.indexOf('.') !== -1) {
value = value.split('.').filter(Boolean).map(tryParseInt);
} else {
value = [tryParseInt(value)];
}
return value;
} else if (typeof value === 'number') {
return [value];
} else {
invariant(
false,
'keyPath can be either an array, a string or a number, got: %s',
value
);
}
}