回答編集履歴
4
冗長だった
answer
CHANGED
@@ -29,11 +29,8 @@
|
|
29
29
|
```js
|
30
30
|
const opt = (obj, attrs) => [...(function* (){
|
31
31
|
for (attr of attrs){
|
32
|
-
if ( obj == null )
|
32
|
+
if ( obj == null ) return undefined;
|
33
|
-
return undefined;
|
34
|
-
} else {
|
35
|
-
|
33
|
+
yield obj = obj[attr];
|
36
|
-
};
|
37
34
|
}
|
38
35
|
})()].slice(-1)[0];
|
39
36
|
|
3
別解2
answer
CHANGED
@@ -14,11 +14,33 @@
|
|
14
14
|
[Can I use... Support tables for HTML5, CSS3, etc](https://caniuse.com/#feat=mdn-javascript_operators_optional_chaining)
|
15
15
|
|
16
16
|
### 別解
|
17
|
-
|
17
|
+
再帰とカリー化でユーティリティ関数を書いてみました。
|
18
18
|
```js
|
19
19
|
const opt = x => attr => attr == null ? x : opt( x == null ? undefined : x[attr] );
|
20
20
|
|
21
21
|
const item = 'xxx';
|
22
22
|
const lang = 'jp';
|
23
23
|
const name = opt(obj)('parent')(item)(lang)() || 'notext';
|
24
|
-
```
|
24
|
+
```
|
25
|
+
|
26
|
+
|
27
|
+
### 別解2
|
28
|
+
今度はジェネレータと早期リターンで書いてみました。イテレータの最後の要素にアクセスする上手い方法はないものか。
|
29
|
+
```js
|
30
|
+
const opt = (obj, attrs) => [...(function* (){
|
31
|
+
for (attr of attrs){
|
32
|
+
if ( obj == null ) {
|
33
|
+
return undefined;
|
34
|
+
} else {
|
35
|
+
yield obj = obj[attr];
|
36
|
+
};
|
37
|
+
}
|
38
|
+
})()].slice(-1)[0];
|
39
|
+
|
40
|
+
const item = 'apple';
|
41
|
+
const lang = 'jp';
|
42
|
+
const name = opt(obj, ['parent', item, lang]) || 'notext';
|
43
|
+
```
|
44
|
+
|
45
|
+
かっこかっこがなくなってウザさが減ったと思います。
|
46
|
+
あと、早期リターンをしているので、浅い階層でプロパティがなかった場合に省コスト、かも?
|
2
軽微な修正
answer
CHANGED
@@ -20,5 +20,5 @@
|
|
20
20
|
|
21
21
|
const item = 'xxx';
|
22
22
|
const lang = 'jp';
|
23
|
-
const name = opt(obj)('parent')(item)(lang)()
|
23
|
+
const name = opt(obj)('parent')(item)(lang)() || 'notext';
|
24
24
|
```
|
1
別解
answer
CHANGED
@@ -11,4 +11,14 @@
|
|
11
11
|
```
|
12
12
|
|
13
13
|
ブラウザ対応状況
|
14
|
-
[Can I use... Support tables for HTML5, CSS3, etc](https://caniuse.com/#feat=mdn-javascript_operators_optional_chaining)
|
14
|
+
[Can I use... Support tables for HTML5, CSS3, etc](https://caniuse.com/#feat=mdn-javascript_operators_optional_chaining)
|
15
|
+
|
16
|
+
### 別解
|
17
|
+
|
18
|
+
```js
|
19
|
+
const opt = x => attr => attr == null ? x : opt( x == null ? undefined : x[attr] );
|
20
|
+
|
21
|
+
const item = 'xxx';
|
22
|
+
const lang = 'jp';
|
23
|
+
const name = opt(obj)('parent')(item)(lang)()// || 'notext';
|
24
|
+
```
|