有沒有內置的功能,你需要什麼。所以你需要制定一個解決方案。
首先你需要把這個任務分成更瑣碎的部分。
一部分會接受陣列的陣列和在其上執行組合:
// 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