Skip to content

performance enhancement #82

@oliverfoster

Description

@oliverfoster

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
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions