-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
62 lines (50 loc) · 1.36 KB
/
index.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
60
61
62
'use strict'
module.exports = (str, find, replace, flags) => {
var gFlag = false
if (typeof str !== 'string') {
throw new TypeError('`str` parameter must be a string!')
}
if (!Array.isArray(find)) {
throw new TypeError('`find` parameter must be an array!')
}
if (!Array.isArray(replace)) {
throw new TypeError('`replace` parameter must be an array!')
}
if (!find.length || !replace.length) {
throw new Error('`find` and `replace` parameters must not be empty!')
}
if (find.length !== replace.length) {
throw new Error('`find` and `replace` parameters must be equal in length!')
}
if (flags) {
if (typeof flags !== 'string') {
throw new TypeError('`flags` parameter must be a string!')
} else if (~flags.indexOf('g')) {
gFlag = true
} else {
flags += 'g'
}
} else {
flags = 'g'
}
var done = []
var joined = find.join(')|(')
var regex = new RegExp('(' + joined + ')', flags)
return str.replace(regex, (match, ...finds) => {
var replaced
finds.some((found, index) => {
if (found !== undefined) {
if (gFlag) {
replaced = replace[index]
} else if (!~done.indexOf(found)) {
done.push(found)
replaced = replace[index]
} else {
replaced = found
}
return true
}
})
return replaced
})
}