回答編集履歴
1
より実践的な書き方も掲載
test
CHANGED
@@ -1,4 +1,4 @@
|
|
1
|
-
真正面からやるとこう、
|
1
|
+
真正面からやるとこう、JavaScriptだと表現力が足りないからRamda.js使うことに…
|
2
2
|
|
3
3
|
ついでにポイントフリーで挑戦。
|
4
4
|
|
@@ -69,3 +69,75 @@
|
|
69
69
|
やることが複雑すぎてそんなに短くならない。
|
70
70
|
|
71
71
|
すぐに二重配列になるからflattenを何度も挟むことになるしね。
|
72
|
+
|
73
|
+
|
74
|
+
|
75
|
+
より関数的にするなら経由する関数に名称付けてこんな感じ
|
76
|
+
|
77
|
+
|
78
|
+
|
79
|
+
```JavaScript
|
80
|
+
|
81
|
+
const R = require('ramda');
|
82
|
+
|
83
|
+
const itemList = [
|
84
|
+
|
85
|
+
{id: 'p1', items: [{id: 1}, {id: 2}, {id: 3}]},
|
86
|
+
|
87
|
+
{id: 'p2', items: [{id: 1}, {id: 10}, {id: 33}]},
|
88
|
+
|
89
|
+
{id: 'p3', items: [{id: 11}, {id: 22}, {id: 33}]}
|
90
|
+
|
91
|
+
];
|
92
|
+
|
93
|
+
const orderList = [
|
94
|
+
|
95
|
+
{id: '1', products: ['p1', 'p2']},
|
96
|
+
|
97
|
+
{id: '2', products: ['p3']}
|
98
|
+
|
99
|
+
];
|
100
|
+
|
101
|
+
|
102
|
+
|
103
|
+
// この関数群を他のファイルにしてrequireすればテストしやすい
|
104
|
+
|
105
|
+
// toUniqProducts :: [{products: [String]}] -> [String]
|
106
|
+
|
107
|
+
const toUniqProducts = R.pipe(R.pluck('products'), R.flatten, R.uniq)
|
108
|
+
|
109
|
+
// toUniqItems :: [String] -> [Object]
|
110
|
+
|
111
|
+
const toUniqItems = R.pipe(
|
112
|
+
|
113
|
+
R.map(R.pipe(R.propEq('id'), R.find(R.__, itemList))),
|
114
|
+
|
115
|
+
R.filter(R.identity),
|
116
|
+
|
117
|
+
R.pluck('items'),
|
118
|
+
|
119
|
+
R.flatten,
|
120
|
+
|
121
|
+
R.uniqBy(R.prop('id'))
|
122
|
+
|
123
|
+
)
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
R.compose(
|
128
|
+
|
129
|
+
R.tap(console.log),
|
130
|
+
|
131
|
+
toUniqItems,
|
132
|
+
|
133
|
+
toUniqProducts,
|
134
|
+
|
135
|
+
)(orderList)
|
136
|
+
|
137
|
+
```
|
138
|
+
|
139
|
+
|
140
|
+
|
141
|
+
Ramda.jsって便利だね!
|
142
|
+
|
143
|
+
素のJSで頑張るならLhankor_Mhyさんのアプローチがエレガント。
|