需求產生的原因是:后端有一些數據是從舊平台直接遷移過來的,新平台需要根據遷移過來的數據,自動生產新的數據格式。
操作符有如下幾種,分項、支路和數字配合操作符可以自定義組合,例如 [000000000001]+<00001>,帶[號的表示type是branch,帶<表示type是sub。
// 操作符列表 operatorList: [ '+', '-', '*', '/', '(', ')', 'inputNumber' ],
舉例:[000000000001]+<00001>
解析為:
[{"type":"branch","name":"1#","value":92501,"electricAddr":"000000000001"},{"type":"+"},{"type":"sub","name":"電電電","value":69640,"number":"00001"}]
部分實現代碼如下:
data () { return { // 操作符列表 operatorList: [ '+', '-', '*', '/', '(', ')', 'inputNumber' ], filterOperator: [], //操作符過濾和排序列表 } method:{ //操作符排序和過濾 geOoperatorFilter (expStr) { let arr = this.operatorList.map(n => { return { index: expStr.indexOf(n), val: n }; }); arr = arr.filter(f => f.index > -1); arr.sort(this.sortId); this.filterOperator = arr.map(m => { return m.val }); // console.log('this.filterOperator :>> ', this.filterOperator); }, sortId (a, b) { return a.index - b.index;//由低到高 }, // true:數值型的,false:非數值型 myIsNaN (value) { return typeof value === 'number' && !isNaN(value); }, //[000000000001]+[11101110011]-<1002>*<c3110> reveserExpress (expStr) { this.geOoperatorFilter(expStr); let arr = []; this.analysisData(arr, expStr); // console.log('arr :>> ', arr); let jsonArr = []; arr.forEach(n => { if (n.includes('[')) { jsonArr.push({ "type": "branch", "name": "", "value": '', "electricAddr": n.replace('[', '').replace(']', '') }); } if (n.includes('<')) { jsonArr.push({ "type": "sub", "name": "", "value": '', "number": n.replace('<', '').replace('>', '') }); } if (this.filterOperator.includes(n)) { jsonArr.push({ "type": n }); } //如果是個數字 if (this.myIsNaN(n)) { jsonArr.push({ "type": 'number', "value": n }); } }); // console.log('jsonArr :>> ', jsonArr); this.form.expressionJson = JSON.stringify(jsonArr); }, //是否包含分隔符 containOperator (word) { return this.filterOperator.some(f => word.includes(f)); }, analysisData (arr, expStr) { // debugger; this.filterOperator.forEach(n => { if (expStr.includes(n)) { // debugger; let tempArr = expStr.split(n); tempArr.forEach((t, index) => { //不包含分隔符 if (!this.containOperator(t) && !arr.includes(t)) { // debugger; arr.push(t); if (index < tempArr.length - 1) { arr.push(n); } } else { // debugger; this.analysisData(arr, t); } }) } }) }, }
測試:
let expStr = '[000000000001]-[11101110011]/<1002>+<c3110>'; this.reveserExpress(expStr);
運行結果:
[{"type":"branch","name":"","value":"","electricAddr":"000000000001"},{"type":"-"},{"type":"branch","name":"","value":"","electricAddr":"11101110011"},
{"type":"/"},{"type":"sub","name":"","value":"","number":"1002"},{"type":"+"},{"type":"sub","name":"","value":"","number":"c3110"}]
雖然很快實現了功能,可是寫這樣的代碼總感覺好惡心,可又不知道該怎么辦?好想打人,可是沒有發泄對象,只好扇自己一巴掌!
眾里尋他千百度,猛一回頭,卧艹,那人卻在一個人過馬路~