A growing collection of interesting JavaScript and TypeScript snippets for fun and future profit.

Generate Excel-style column headers

This function generates column headers A...Z then starts two-letter combinations AA, AB...AZ, BA...BZ , and then three-letter combinations, etc, to an infinite degree.

function* columnHeaderGenerator() {
  const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  for (const letter of letters) yield letter
  const g = columnHeaderGenerator()
  while (true) {
    const l1 = g.next().value
    for (const l2 of letters) yield l1 + l2
  }
}
 
// Example usage
const generator = columnHeaderGenerator()
console.log(generator.next().value) // -> A
console.log(generator.next().value) // -> B
// ...
console.log(generator.next().value) // -> Z
console.log(generator.next().value) // -> AA
console.log(generator.next().value) // -> AB

Programmatically trigger a browser download

Sometimes a file or arbitrary generated data needs to be downloaded without the user having clicked a download link (e.g. an asynchronous process has just finished) and this seems to be the standard way to do it.

// Note: only works with same-origin or blob/data URLs
function downloadFileAtURL(url: string, asFilename: string) {
  var link = document.createElement('a');
  link.download = asFilename;
  link.href = url;
  link.click();
}
 
function downloadBlob(blob: Blob, asFilename: string) {
  const blobUrl = URL.createObjectURL(blob)
  downloadFileAtURL(blobUrl, asFilename)
  URL.revokeObjectURL(blobUrl)
}
 
// Example usage
const csvString = "fruit, price\napple, 3.5\nbanana, 3.0\norange, 4.2"
const csvBlob = new Blob([ csvString ], { type: "text/csv" });
downloadBlob(csvBlob, "fruit_prices.csv")