teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

より実践的な書き方も掲載

2017/09/29 01:46

投稿

miyabi-sun
miyabi-sun

スコア21472

answer CHANGED
@@ -1,4 +1,4 @@
1
- 真正面からやるとこう、ライブラリが足りないからRamda.js使ったよ。
1
+ 真正面からやるとこう、JavaScriptだと表現力が足りないからRamda.js使うことに…
2
2
  ついでにポイントフリーで挑戦。
3
3
 
4
4
  ```JavaScript
@@ -33,4 +33,40 @@
33
33
  ```
34
34
 
35
35
  やることが複雑すぎてそんなに短くならない。
36
- すぐに二重配列になるからflattenを何度も挟むことになるしね。
36
+ すぐに二重配列になるからflattenを何度も挟むことになるしね。
37
+
38
+ より関数的にするなら経由する関数に名称付けてこんな感じ
39
+
40
+ ```JavaScript
41
+ const R = require('ramda');
42
+ const itemList = [
43
+ {id: 'p1', items: [{id: 1}, {id: 2}, {id: 3}]},
44
+ {id: 'p2', items: [{id: 1}, {id: 10}, {id: 33}]},
45
+ {id: 'p3', items: [{id: 11}, {id: 22}, {id: 33}]}
46
+ ];
47
+ const orderList = [
48
+ {id: '1', products: ['p1', 'p2']},
49
+ {id: '2', products: ['p3']}
50
+ ];
51
+
52
+ // この関数群を他のファイルにしてrequireすればテストしやすい
53
+ // toUniqProducts :: [{products: [String]}] -> [String]
54
+ const toUniqProducts = R.pipe(R.pluck('products'), R.flatten, R.uniq)
55
+ // toUniqItems :: [String] -> [Object]
56
+ const toUniqItems = R.pipe(
57
+ R.map(R.pipe(R.propEq('id'), R.find(R.__, itemList))),
58
+ R.filter(R.identity),
59
+ R.pluck('items'),
60
+ R.flatten,
61
+ R.uniqBy(R.prop('id'))
62
+ )
63
+
64
+ R.compose(
65
+ R.tap(console.log),
66
+ toUniqItems,
67
+ toUniqProducts,
68
+ )(orderList)
69
+ ```
70
+
71
+ Ramda.jsって便利だね!
72
+ 素のJSで頑張るならLhankor_Mhyさんのアプローチがエレガント。