Finding the minimum length of a stringified JS string, prioritizing what's already chosen

Viewed 20

So I've got this algorithm here, and with it I want to find out what is the shortest output of the same string in JavaScript's three different kinds of string literals, prioritizing what is chosen in chosenQuoteStyle and falling back to the next quoting style, if defined in the pool.

In most cases, when all the expansions are of the same length and don't contain any escaped characters, the algorithm will choose whichever is first in the quoting pool, yet I am unable to determine how to fall back if two of the quoting styles has a similar expansion length.

jsesc is a function that returns a stringified representation of a JavaScript literal, for those unaware.

const jsesc = require("jsesc")
const string = '!"`'
const chosenQuoteStyle = ["backtick", "double"]

const single = jsesc(string, {quotes: "single", wrap: true})
const double = jsesc(string, {quotes: "double", wrap: true})
const backtick = jsesc(string, {quotes: "backtick", wrap: true})

const lengthMap = [
  {type: "single", string: single, length: single.length},
  {type: "double", string: double, length: double.length},
  {type: "backtick", string: backtick, length: backtick.length},
]
const lengths = lengthMap
  .map(({type, length}) => length)
  .sort(({length: a}, {length: b}) => a - b)
if (new Set(lengths).size != 1) {
  current = lengthMap[0].type
  return jsesc(string, {quotes: current, wrap: true})
} else {
  current = quoteSequence[0]
  return jsesc(string, {quotes: current, wrap: true})
}
0 Answers
Related