Skip to content

Instantly share code, notes, and snippets.

@shuhrat
Created December 8, 2012 10:44
Show Gist options
  • Save shuhrat/4239756 to your computer and use it in GitHub Desktop.
Save shuhrat/4239756 to your computer and use it in GitHub Desktop.
I had wondered how google does it, now I know that it is not as hard as I thought

Challenge source

function Dictionary(vocabulary) {
  var counter = 0,
      length = vocabulary.length,
      cache = {},
      position = function(counter) {
        var word, remainder;
        if (counter in cache) return cache[counter];
        word = vocabulary[counter % length],
        remainder = ~~(counter / length);

        if (remainder == 0) {
          return cache[counter] = word;
        } else {
          return cache[counter] = position(remainder - 1) + word;
        }
      };

  return {
    next: function() {
      return position(counter++);
    }
  };
}

function classNamePreprocessor(classes, vocabulary) {
  var unique = {},
      unique_list = [],
      class_name = null,
      dictionary = Dictionary(vocabulary),
      i;

  i = classes.length;
  while(i--) {
    class_name = classes[i];
    if (!(class_name in unique)) {
      unique[class_name] = {
        count: 0,
        name: class_name
      };
      unique_list.push(unique[class_name]);
    }
    unique[class_name].count++;
  }

  unique_list.sort(function(a, b) {
    return a.count - b.count;
  });

  i = unique_list.length;
  while(i--) {
    delete unique_list[i].count;
    unique_list[i].short = dictionary.next();
  }

  return unique;
}

var classes = [
  'b-statcounter',
  'b-statcounter__metrika',
  'b-statcounter__metrika_type_js',
  'i-bem',
  'b-search__table',
  'b-form-input',
  'b-form-input_theme_grey',
  'b-form-input_size_l',
  'i-bem',
  'b-form-input__input',
  'b-search__button',
  'b-form-button__content',
  'b-form-button__text',
  'b-form-button__input',
  'i-bem',
  'b-main-menu',
  'b-main-menu__tab',
  'b-main-menu__tab',
  'b-main-menu__tab',
  'b-main-menu__tab',
  'b-main-menu__tab_type_selected',
  'b-main-menu__tab',
  'b-main-menu__tab_type_selected',
  'l-page__right',
  'b-static-text',
  'b-static-text',
  'b-foot__layout-column',
  'b-foot__layout-column_type_left',
  'b-link',
  'b-foot__link',
  'b-foot__layout-column',
  'b-foot__layout-column',
  'b-foot__layout-column_type_center',
  'b-link',
  'b-foot__link',
  'b-foot__layout-column',
  'b-foot__layout-column_type_penultima',
  'b-link',
  'b-foot__link',
  'b-foot__layout-column',
  'b-foot__layout-column_type_right',
  'b-copyright__link',
  'b-foot__layout-gap-i'
  ],
  vocabulary = ['a', 'b', 'c', 'd'],
  preprocessed = classNamePreprocessor(classes, vocabulary);

console.log(preprocessed);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment