1 | # idx
|
2 |
|
3 | `idx` is a utility function for traversing properties on objects and arrays.
|
4 |
|
5 | If an intermediate property is either null or undefined, it is instead returned.
|
6 | The purpose of this function is to simplify extracting properties from a chain
|
7 | of maybe-typed properties.
|
8 |
|
9 | ## Usage
|
10 |
|
11 | Consider the following type:
|
12 |
|
13 | ```
|
14 | const props: {
|
15 | user: ?{
|
16 | name: string,
|
17 | friends: ?Array<User>,
|
18 | }
|
19 | };
|
20 | ```
|
21 |
|
22 | Getting to the friends of my first friend would resemble:
|
23 |
|
24 | ```
|
25 | props.user &&
|
26 | props.user.friends &&
|
27 | props.user.friends[0] &&
|
28 | props.user.friends[0].friends
|
29 | ```
|
30 |
|
31 | Instead, `idx` allows us to safely write:
|
32 |
|
33 | ```
|
34 | idx(props, _ => _.user.friends[0].friends)
|
35 | ```
|
36 |
|
37 | The second argument must be a function that returns one or more nested member
|
38 | expressions. Any other expression has undefined behavior.
|
39 |
|
40 | ## Babel Transform
|
41 |
|
42 | The `idx` runtime function exists for the purpose of illustrating the expected
|
43 | behavior and is not meant to be executed. The `idx` function is used in
|
44 | conjunction with a Babel plugin that replaces it with better performing code:
|
45 |
|
46 | ```
|
47 | props.user == null ? props.user :
|
48 | props.user.friends == null ? props.user.friends :
|
49 | props.user.friends[0] == null ? props.user.friends[0] :
|
50 | props.user.friends[0].friends
|
51 | ```
|
52 |
|
53 | All this machinery exists due to the fact that an existential operator does not
|
54 | currently exist in JavaScript.
|
55 |
|
56 | ## License
|
57 |
|
58 | `idx` is [BSD licensed](./LICENSE). We also provide an additional
|
59 | [patent grant](./PATENTS).
|