1 | ;
|
2 |
|
3 | const t = require('babel-types');
|
4 |
|
5 | // accessSafe wraps memberExpressions in object/null checks
|
6 | // TODO: inject this as a function? this gets pretty repetitive
|
7 | function accessSafe(obj, member) {
|
8 | return t.logicalExpression(
|
9 | '&&',
|
10 | t.logicalExpression(
|
11 | '&&',
|
12 | // typeof obj === 'object
|
13 | t.binaryExpression(
|
14 | '===',
|
15 | t.unaryExpression('typeof', obj),
|
16 | t.stringLiteral('object')
|
17 | ),
|
18 | // obj !== null
|
19 | t.binaryExpression('!==', obj, t.nullLiteral())
|
20 | ),
|
21 | // obj.member
|
22 | t.memberExpression(obj, t.identifier(member), false)
|
23 | );
|
24 | }
|
25 |
|
26 | module.exports = accessSafe;
|