|
export default function stringQuoteOnlyIfNecessaryFormatter( |
|
opts: StringFQuoteOnlyIfNecesaryFormatterOptions = {}, |
|
): Formatter<string> { |
|
const quote = typeof opts.quote === 'string' ? opts.quote : '"'; |
|
const escapedQuote = |
|
typeof opts.escapedQuote === 'string' |
|
? opts.escapedQuote |
|
: `${quote}${quote}`; |
|
const separator = typeof opts.separator === 'string' ? opts.separator : ','; |
|
const eol = typeof opts.eol === 'string' ? opts.eol : '\n'; |
|
|
|
const stringFormatter = defaulStringFormatter({ quote, escapedQuote }); |
|
|
|
return (value) => { |
|
if ([quote, separator, eol].some((char) => value.includes(char))) { |
|
return stringFormatter(value); |
|
} |
|
|
|
return value; |
|
}; |
|
} |
|
if ([quote, separator, eol].some((char) => value.includes(char))) { |
Line 26 unnecessarily creates a new array every time. It could easily be cached.
const chars = [quote, separator, eol]
return (value) => {
if (chars.some((char) => value.includes(char))) {
return stringFormatter(value)
}
return value
}
Constructing a regular expression rather than the loops may be quicker but would need testing. String.prototype.search returns the index of the first occurrence.
const chars = new RegExp(`[${quote}${separator}${eol}]{1}`)
return (value) => {
if (value.search(chars) > -1) {
return stringFormatter(value)
}
return value
}
json2csv/packages/formatters/src/stringQuoteOnlyIfNecessary.ts
Lines 12 to 32 in f961d15
json2csv/packages/formatters/src/stringQuoteOnlyIfNecessary.ts
Line 26 in f961d15
Line 26 unnecessarily creates a new array every time. It could easily be cached.
Constructing a regular expression rather than the loops may be quicker but would need testing. String.prototype.search returns the index of the first occurrence.