-
Notifications
You must be signed in to change notification settings - Fork 0
/
accounts-merge.js
59 lines (47 loc) · 1.42 KB
/
accounts-merge.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* @param {string[][]} accounts
* @return {string[][]}
*/
var accountsMerge = function(accounts) {
// list 1 => user 1 email1 email2
// list 2 => user 2 email3 email4
// list 3 => user 3 email3 email4
// ...
// for each list, check if email is used or not, if so, merge the user
// User < name, emails>
// Map<email, user>
// Set<User>, to merge, update the emails of user, update Map<email, user>
const users = new Set()
// for User, ['name', Set<email:string>]
const emailUserMap = new Map()
const merge = (userFrom, userTo) => {
if (userFrom === userTo) return
users.delete(userFrom)
// update all the email , link to userTo
// add email to userTo
for (let email of userFrom[1]) {
emailUserMap.set(email, userTo)
userTo[1].add(email)
}
}
for (let account of accounts) {
const [name, ...emails] = account
const user = [name, new Set()]
users.add(user)
for (let email of emails) {
if (emailUserMap.has(email)) {
merge(emailUserMap.get(email), user)
} else {
emailUserMap.set(email, user)
user[1].add(email)
}
}
}
const result = []
for (let user of users) {
const list = [...user[1]].sort()
list.unshift(user[0])
result.push(list)
}
return result
};