)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Mini Markdown Parser

  1. function mark(str) {
  2.   const lines = str.split`\n`;
  3.   let wasLi;
  4.  
  5.   for (let i = 0; i < lines.length; i++) {
  6.     const curr = lines[i];
  7.     const line = curr.trim();
  8.     const hdr = line.split`#`.length - 1;
  9.  
  10.     if (line === '') { 
  11.       lines[i] = '<br>';
  12.     } else if (hdr > 0) {
  13.       lines[i] = `<h${hdr} style="margin-bottom:0">
  14.         ${curr.replace(/#/g, '')}</h${hdr}>`;
  15.     } else if (line === '***') {
  16.       lines[i] = '<hr>';
  17.     } else if (line.startsWith('- ')) {
  18.       lines[i] = `${!wasLi ? '<ul>' : ''}
  19.         <li>${curr.replace(/-\s+/, '')}</li>`;
  20.       wasLi = true;
  21.     } else if (wasLi) {
  22.       lines[i - 1] += '</ul>\n';
  23.       wasLi = false;
  24.     }
  25.   }
  26.  
  27.   return lines.join`\n`
  28.     .replace(/\*\*(.+)\*\*/gm, '<b>$1</b>')
  29.     .replace(/_(.+)_/gm, '<i>$1</i>')
  30.     .replace(/~~(.+)~~/gm, '<strike>$1</strike>')
  31.     .replace(/`(.+)`/gm, '<code>$1</code>');
  32. }
  33.  
  34. // try it out
  35.  
  36. const md = document.body.appendChild(document.createElement('div'));
  37. md.style.fontFamily = 'sans-serif';
  38. md.innerHTML = `# Mini Markdown Subset
  39.  
  40. This is a subset of markdown stuff
  41.  
  42. ## It includes
  43.  
  44. - headers
  45. - **bold styles**
  46. - _italic styles, <br> multiline fine..._
  47. - \`code style\`
  48.  
  49. Other than ~~strikethrough~~ that is pretty much it... oh and **hr** tags
  50. ***
  51. ***
  52. _here is some italic text with some bold text **nested** <br>within it etc..._
  53. `;
  54. md.innerHTML = mark(md.innerHTML);

This code takes a string and formats a few parts of it with markdown syntax. This only handles a small subset of actual markdown.

I was thinking about markdown in code comments last night as I was working on a forthcoming snippet.zone github repo. Anyway, I decided to speed-code the main things I find myself using in markdown so that maybe I can do markdown formatted comments at some point…

Random Negative or Positive

  1. Math.round(Math.random()) * 2 - 1;

Randomly generate either -1 or 1. There are many ways to do this.

Save Large Canvas

  1. // https://stackoverflow.com/questions/38781968/problems-downloading-big-filemax-15-mb-on-google-chrome
  2. function dataUriToBlob(dataURI) {
  3.   const binStr = atob(dataURI.split(',')[1]);
  4.   const len = binStr.length;
  5.   const arr = new Uint8Array(len);
  6.   const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  7.   for (let i = 0; i < len; i++) {
  8.     arr[i] = binStr.charCodeAt(i);
  9.   }
  10.  
  11.   const blob = new Blob([arr], {
  12.     type: mimeString
  13.   });
  14.  
  15.   return URL.createObjectURL(blob);
  16. }
  17.  
  18. const save = document.createElement('a');
  19. save.innerText = 'save this big image';
  20. document.body.appendChild(save);
  21.  
  22. const canvas = document.createElement('canvas');
  23. const c = canvas.getContext('2d');
  24.  
  25. canvas.width = window.innerWidth * 4;
  26. canvas.height = window.innerHeight * 4;
  27. canvas.style.transformOrigin = '0 0';
  28. canvas.style.transform = `scale(0.14)`;
  29. document.body.appendChild(canvas);
  30.  
  31. c.fillStyle = 'black';
  32. c.fillRect(0, 0, canvas.width, canvas.height);
  33.  
  34. const size = Math.max(window.innerWidth, window.innerHeight);
  35.  
  36. // draw some rectangles
  37. c.globalCompositeOperation = 'difference'
  38. for (let i = 0; i < 100; i++) {
  39.   const angle = Math.random() * 180 + 180;
  40.   const color = `hsl(${angle}deg, 50%, 50%)`;
  41.   c.fillStyle = color;
  42.   const width = Math.random() * size + 100;
  43.   const height = Math.random() * size + 100;
  44.   const x = Math.random() * canvas.width - width / 2;
  45.   const y = Math.random() * canvas.height - height / 2;
  46.   c.fillRect(
  47.     x, 
  48.     y, 
  49.     width, 
  50.     height);
  51. }
  52.  
  53. save.download = 'big-image';
  54. save.href = dataUriToBlob(canvas.toDataURL());

Weirdly if you try to save a massive data URI to a file (> 15mb) it will just fail. In order to do this properly, you need to convert to a blob first and then save. I encountered this at some point and learned of the solution from user doppelgreener over at stack overflow. Take a look at the post here.

Golfed join

  1. const str = ['one','-','two'].join``;
  2. console.log(str);
  3. // outputs "one-two"

With tagged templates you can pass a template string to a function without parens.

Make Math Global

  1. Object.getOwnPropertyNames(Math).forEach(i => window[i] = Math[i]);
  2.  
  3. // or with map, just to be shorter
  4. Object.getOwnPropertyNames(Math).map(i => window[i] = Math[i]);
  5.  
  6. // if this points to window
  7. Object.getOwnPropertyNames(Math).map(i => this[i] = Math[i]);
  8.  
  9. // or using the deprecated "with" statement
  10. with (Math) {
  11.   console.log(PI, E, SQRT2, cos(1));
  12. }

While not very useful, I sometimes like to make the entire Math object global on the window – just when speed coding and playing around.

snippet.zone ~ 2021-24 /// {s/z}