Files
omni-tools/src/pages/tools/csv/swap-csv-columns/service.ts

62 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-03-31 18:08:22 +00:00
import { splitCsv } from '@utils/csv';
2025-04-01 15:40:19 +00:00
import { InitialValuesType } from './types';
2025-03-31 18:08:22 +00:00
function retrieveFromAndTo(
headerRow: string[],
2025-04-01 15:40:19 +00:00
options: InitialValuesType
2025-03-31 18:08:22 +00:00
): number[] {
2025-04-01 15:40:19 +00:00
const from = options.fromPositionStatus
? Number(options.fromPosition)
: headerRow.findIndex((header) => header === options.fromHeader) + 1;
2025-03-31 18:08:22 +00:00
2025-04-01 15:40:19 +00:00
const to = options.toPositionStatus
? Number(options.toPosition)
: headerRow.findIndex((header) => header === options.toHeader) + 1;
2025-03-31 18:08:22 +00:00
if (from <= 0 || to <= 0)
throw new Error('Invalid column positions. Check headers or positions.');
if (from > headerRow.length || to > headerRow.length)
throw new Error(`There are only ${headerRow.length} columns`);
return [from, to];
}
function swap(lines: string[][], from: number, to: number): string[][] {
if (from <= 0 || to <= 0)
throw new Error('Columns position must be greater than zero ');
return lines.map((row) => {
const newRow = [...row]; // Clone the row to avoid mutating the original
[newRow[from - 1], newRow[to - 1]] = [newRow[to - 1], newRow[from - 1]]; // Swap values
return newRow;
});
}
2025-04-01 15:40:19 +00:00
export function csvColumnsSwap(input: string, options: InitialValuesType) {
2025-03-31 18:08:22 +00:00
if (!input) {
return '';
}
// split csv input and remove comments
2025-04-01 15:40:19 +00:00
const rows = splitCsv(
input,
options.deleteComment,
options.commentCharacter,
options.emptyLines
);
2025-03-31 18:08:22 +00:00
const columnCount = Math.max(...rows.map((row) => row.length));
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < columnCount; j++) {
if (!rows[i][j]) {
2025-04-01 15:40:19 +00:00
rows[i][j] = options.emptyValuesFilling ? '' : options.customFiller;
2025-03-31 18:08:22 +00:00
}
}
}
2025-04-01 15:40:19 +00:00
const positions = retrieveFromAndTo(rows[0], options);
2025-03-31 18:08:22 +00:00
const result = swap(rows, positions[0], positions[1]);
return result.join('\n');
}