class DataMerger { constructor({ defaultValue = null, clearAllEmptyColumns = true, clearAllEmptyRows = true, // autoSort = false, } = {}) { this.x = [] this.o = {} this.defaultValue = defaultValue this.clearAllEmptyColumns = clearAllEmptyColumns this.clearAllEmptyRows = clearAllEmptyRows } clear() { this.x = [] this.o = {} } clearRow(rowName) { delete this.o[rowName] } clearColumnByName(name) { const i =this.x.indexOf(name) if (i === -1) { return } this.clearColumnByIndex(i) } clearColumnByIndex(i) { delete this.x[i] this.x = this.x.flat() for (let key of Object.keys(this.o)) { delete this.o[key][i] this.o[key] = this.o[key].flat() } } merge(columnNames, data, rowName = 'default') { if (!this.o[rowName]) { let newList = [] for (let i in this.x) { newList.push(this.defaultValue) } this.o[rowName] = newList } for (let i in columnNames) { let index = this.x.indexOf(columnNames[i]) if (index === -1) { this.x.push(columnNames[i]) for (let row of Object.values(this.o)) { row.push(this.defaultValue) } index = this.x.length - 1 } this.o[rowName][index] = data[i] } if (this.clearAllEmptyRows) { for (let key of Object.keys(this.o)) { let allowToClear = true for (let item of this.o[key]) { if (item !== this.defaultValue) { allowToClear = false break } } if (allowToClear) { this.clearRow(key) } } } if (this.clearAllEmptyColumns) { for (let i = 0; i < this.x.length; i++) { let allowToClear = true for (let item of Object.values(this.o)) { if (item[i] !== this.defaultValue) { allowToClear = false break } } if (allowToClear) { this.clearColumnByIndex(i) i-- } } } } getColumnNames() { return this.x } getData() { return this.o } }