l0bsterssg

node.js static responsive blog post generator
Log | Files | Refs | README

Slugger.js (1263B)


      1 /**
      2  * Slugger generates header id
      3  */
      4 module.exports = class Slugger {
      5   constructor() {
      6     this.seen = {};
      7   }
      8 
      9   serialize(value) {
     10     return value
     11       .toLowerCase()
     12       .trim()
     13       // remove html tags
     14       .replace(/<[!\/a-z].*?>/ig, '')
     15       // remove unwanted chars
     16       .replace(/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,./:;<=>?@[\]^`{|}~]/g, '')
     17       .replace(/\s/g, '-');
     18   }
     19 
     20   /**
     21    * Finds the next safe (unique) slug to use
     22    */
     23   getNextSafeSlug(originalSlug, isDryRun) {
     24     let slug = originalSlug;
     25     let occurenceAccumulator = 0;
     26     if (this.seen.hasOwnProperty(slug)) {
     27       occurenceAccumulator = this.seen[originalSlug];
     28       do {
     29         occurenceAccumulator++;
     30         slug = originalSlug + '-' + occurenceAccumulator;
     31       } while (this.seen.hasOwnProperty(slug));
     32     }
     33     if (!isDryRun) {
     34       this.seen[originalSlug] = occurenceAccumulator;
     35       this.seen[slug] = 0;
     36     }
     37     return slug;
     38   }
     39 
     40   /**
     41    * Convert string to unique id
     42    * @param {object} options
     43    * @param {boolean} options.dryrun Generates the next unique slug without updating the internal accumulator.
     44    */
     45   slug(value, options = {}) {
     46     const slug = this.serialize(value);
     47     return this.getNextSafeSlug(slug, options.dryrun);
     48   }
     49 };