| /******************************************************************************** |
| * Copyright (c) 2020 Contributors to the Eclipse Foundation |
| * |
| * See the NOTICE file(s) distributed with this work for additional |
| * information regarding copyright ownership. |
| * |
| * This program and the accompanying materials are made available under the |
| * terms of the Eclipse Public License 2.0 which is available at |
| * http://www.eclipse.org/legal/epl-2.0 |
| * |
| * SPDX-License-Identifier: EPL-2.0 |
| ********************************************************************************/ |
| |
| import {arrayJoin} from "../store"; |
| |
| /** |
| * Parses a string as CSV file and returns it entries in a list of arrays. |
| * @param text String in CSV format. |
| * @param separator Separator which is used in the CSV format. |
| */ |
| export function parseCsv(text: string, separator: string): string[][] { |
| return text |
| .replace(new RegExp("\r", "g"), "") |
| .split("\n") |
| .map((row) => row.split(separator)); |
| } |
| |
| /** |
| * Reduces a single row of entries to a CSV string. |
| * @param dataRow List of values to reduce. |
| * @param separator Separator which is used in the CSV format. |
| */ |
| export function reduceRowToCsv(dataRow: string[], separator: string): string { |
| return arrayJoin(dataRow) |
| .reduce<string>((result, rowString) => result + separator + rowString, "") |
| .slice(separator.length); |
| } |
| |
| /** |
| * Reduces a table of entries to a CSV string. |
| * @param data Entries of the table to reduce. |
| * @param separator Separator which is used in the CSV format. |
| */ |
| export function reduceToCsv(data: string[][], separator: string): string { |
| const rowLength = Math.max(...data.map((row) => row.length)); |
| return reduceRowToCsv( |
| data |
| .map<string[]>((row) => { |
| row = [...row]; |
| while (row.length < rowLength) { |
| row.push(""); |
| } |
| return row; |
| }) |
| .map<string>((row) => reduceRowToCsv(row, separator)), |
| "\r\n" |
| ); |
| } |