      1 /**
      2  * Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS-IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16
     17 exports.createAttributePool = function () {
     18   var p = {};
     19   p.numToAttrib = {}; // e.g. {0: ['foo','bar']}
     20   p.attribToNum = {}; // e.g. {'foo,bar': 0}
     21   p.nextNum = 0;
     22
     23   p.putAttrib = function (attrib, dontAddIfAbsent) {
     24     var str = String(attrib);
     25     if (str in p.attribToNum) {
     26       return p.attribToNum[str];
     27     }
     28     if (dontAddIfAbsent) {
     29       return -1;
     30     }
     31     var num = p.nextNum++;
     32     p.attribToNum[str] = num;
     33     p.numToAttrib[num] = [String(attrib[0] || ''), String(attrib[1] || '')];
     34     return num;
     35   };
     36
     37   p.getAttrib = function (num) {
     38     var pair = p.numToAttrib[num];
     39     if (!pair) {
     40       return pair;
     41     }
     42     return [pair[0], pair[1]]; // return a mutable copy
     43   };
     44
     45   p.getAttribKey = function (num) {
     46     var pair = p.numToAttrib[num];
     47     if (!pair) return '';
     48     return pair[0];
     49   };
     50
     51   p.getAttribValue = function (num) {
     52     var pair = p.numToAttrib[num];
     53     if (!pair) return '';
     54     return pair[1];
     55   };
     56
     57   p.eachAttrib = function (func) {
     58     for (var n in p.numToAttrib) {
     59       var pair = p.numToAttrib[n];
     60       func(pair[0], pair[1]);
     61     }
     62   };
     63
     64   p.toJsonable = function () {
     65     return {
     66       numToAttrib: p.numToAttrib,
     67       nextNum: p.nextNum
     68     };
     69   };
     70
     71   p.fromJsonable = function (obj) {
     72     p.numToAttrib = obj.numToAttrib;
     73     p.nextNum = obj.nextNum;
     74     p.attribToNum = {};
     75     for (var n in p.numToAttrib) {
     76       p.attribToNum[String(p.numToAttrib[n])] = Number(n);
     77     }
     78     return p;
     79   };
     80
     81   return p;
     82 }
     83