有没有内置的功能,你需要什么。所以你需要制定一个解决方案。
首先你需要把这个任务分成更琐碎的部分。
一部分会接受阵列的阵列和在其上执行组合:
// Converts [['a'], ['b', 'c']] to ['ab', 'ac']
const combination = (parts) => {
let current = [[]]
parts.forEach(v => {
let result = []
current.forEach(c => {
v.forEach(n => {
result.push(c.concat(n))
})
})
current = result
})
return current.map(v => v.join(' '))
}
另一部分需要的输入转换成数组的数组和格式的输出:
const generate = (formats) => {
let result = []
// Converts [['a'], ['b', 'c']] to ['ab', 'ac']
const combination = (parts) => {
let current = [[]]
parts.forEach(v => {
let result = []
current.forEach(c => {
v.forEach(n => {
result.push(c.concat(n))
})
})
current = result
})
return current.map(v => v.join(' '))
}
formats.split('|').forEach((format) => {
let parts = format
.split(/[\]\[\)\(]/) // split "[a] (b) c" to ["a", "b", "c"]
.filter(String) // remove empy elements
.map(s => {return s.trim()})
.filter(String) // there can be empty strings. remove those too
parts = parts.map(part => {return part.split('/')})
result = result.concat(combination(parts))
})
return result
}
let input = "[my/your/his/her] (best/true) friend is | [who/where] is [your/her/his](best/true) friend"
generate(input).forEach((v, i) => {console.log((i+1) + '. ' + v)})
这几乎是你需要的。虽然有一些角落案件应该被覆盖,并且.split(/[\]\[\)\(]/)
行有点问题。但我相信你可以修复它。
写一堆循环。 – 2017-05-06 11:15:21