在开发中,遇到一个需求,需要将一组数据,将连续出现的部分压缩成 n*y
的形式,比如:20 30 30 20
压缩后的结果应为
20 2x30 20
同时也要对压缩的数据进行解压还原。
压缩数据算法实现:
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
|
export function compressArray(arr, productSign = 'x') { if (!Array.isArray(arr)) return arr
const result = [] let count = 1
for (let i = 0; i < arr.length; i++) { if (i === arr.length - 1 || arr[i] !== arr[i + 1]) { if (count > 1) { result.push(count + productSign + arr[i]) } else { result.push(arr[i]) } count = 1 } else { count++ } }
return result }
compressArray([20,30,30,20])
|
解压数据算法实现:
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
|
export function formatStringToArray(str, returnString = false, separator = ',') { let results = [] if (typeof str !== 'string') results = [str] else { results = str.split(/,|:|;|\s+|,|;|。|\-|~|\+/) }
const newResults = [] const regex = /(\d+)([xX*])(\d+)/ results.forEach(item => { const match = item.match(regex) if (match) { const count = parseInt(match[1], 10) const value = parseInt(match[3], 10) for (let i = 0; i < count; i++) { newResults.push(value) } } else { newResults.push(item) } }) if (returnString) return newResults.join(separator) return newResults }
formatStringToArray("20 2*30 20") formatStringToArray("20 2*30 20",true)
|