Функция неправильно экранирует кавычки из элементов, как можно это сделать?

function arrayToCsv(data) {
  let result = data
    .map((array) =>
      array
        .map((e) => {
          let type = typeof e;
          if (type !== "number" && type !== "string")
            throw new Error("Unexpected value");
          //
          if (type === "string" && e.includes(",")) {
            return JSON.stringify(e);
          } else return e;
        })
        .join(",")
    )
    .join("\n");
  return result;
}

Функция, которая переводит двумерный массив (массив массивов) в CSV формат и возвращает строку. Кавычки должны становиться двойными. Код должен корректно экранировать кавычки, в тестах выдает ошибку. Expected: """"text""","other ""long"" text"" Received: ""text",other "long" text"

  55 |   it('корректно экранирует кавычки', () => {
  56 |     const data1 = [['"text"', 'other "long" text']];
> 57 |     expect(arrayToCsv(data1)).toBe('"""text""","other ""long"" text"');

Ответы (1 шт):

Автор решения: Рустам Салимов
function arrayToCsv(data) {


let result = data
    .map((array) =>
      array
        .map((e) => {


  let type = typeof e;
      if (type !== "number" && type !== "string")
        throw new Error("Unexpected value");

      return type === "string" && e.length > 1
        ? '"' + e.replace(/\"/g, '""') + '"'
        : e;
    })
    .join(",")
)
.join("\n");
  return result;
}
→ Ссылка