func([[1, 2], ['a', 'b']]) // '1,2
a,b'
func([[1, 2], ['a,b', 'c,d']]) // '1,2
"a,b","c,d"'
function func(arr) {
return arr
.map(array => array.map(e => {
let type = typeof e;
if (type !== "number" && type !== "string")
throw new Error("Unexpected value");
return (type === "string" && e.includes(",")) ? JSON.stringify(e) : e;
}).join(","))
.join("\n");
}
"
, в том случае, если они есть в строке.function escape(value, char = '"') {
const preparedValue = value?.toString() ?? String(value);
if (preparedValue.includes(char)) {
const escapedValue = preparedValue.replaceAll(char, char.repeat(2));
return char + escapedValue + char;
}
return preparedValue;
}
function toCSV(entries) {
return entries
.map((row) => row
.map((entry) => {
if (typeof entry === 'object') {
throw new Error('Unexpected value');
}
return escape(entry);
})
.join(',')
)
.join('\n');
}
console.assert(toCSV([]) === ``);
console.assert(toCSV([[]]) === ``);
console.assert(toCSV([['name', 'age']]) === `name,age`);
console.assert(toCSV([['name', 'age'], ['John', 30]]) === `name,age
John,30`);
console.assert(toCSV([[1, 2], ['a', 'b']]) === `1,2
a,b`);
console.assert(toCSV([[1, 2], ['a', 'b'], ['c', 'd']]) === `1,2
a,b
c,d`);
console.assert(toCSV([['"text"', 'other "long" text']]) === `"""text""","other ""long"" text"`);