splay.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. define("dojox/encoding/compression/splay", [
  2. "dojo/_base/lang", // dojo.extend
  3. "../bits"
  4. ], function(lang, bits) {
  5. var compression = lang.getObject("dojox.encoding.compression", true);
  6. /*=====
  7. compression = dojox.encoding.compression;
  8. =====*/
  9. compression.Splay = function(n){
  10. this.up = new Array(2 * n + 1);
  11. this.left = new Array(n);
  12. this.right = new Array(n);
  13. this.reset();
  14. };
  15. lang.extend(compression.Splay, {
  16. reset: function(){
  17. for(var i = 1; i < this.up.length; this.up[i] = Math.floor((i - 1) / 2), ++i);
  18. for(var i = 0; i < this.left.length; this.left[i] = 2 * i + 1, this.right[i] = 2 * i + 2, ++i);
  19. },
  20. splay: function(i){
  21. var a = i + this.left.length;
  22. do{
  23. var c = this.up[a];
  24. if(c){ // root
  25. // rotated pair
  26. var d = this.up[c];
  27. // swap descendants
  28. var b = this.left[d];
  29. if(c == b){
  30. b = this.right[d];
  31. this.right[d] = a;
  32. } else {
  33. this.left[d] = a;
  34. }
  35. this[a == this.left[c] ? "left" : "right"][c] = b;
  36. this.up[a] = d;
  37. this.up[b] = c;
  38. a = d;
  39. }else{
  40. a = c;
  41. }
  42. }while(a); // root
  43. },
  44. encode: function(value, stream){
  45. var s = [], a = value + this.left.length;
  46. do{
  47. s.push(this.right[this.up[a]] == a);
  48. a = this.up[a];
  49. }while(a); // root
  50. this.splay(value);
  51. var l = s.length;
  52. while(s.length){ stream.putBits(s.pop() ? 1 : 0, 1); }
  53. return l;
  54. },
  55. decode: function(stream){
  56. var a = 0; // root;
  57. do{
  58. a = this[stream.getBits(1) ? "right" : "left"][a];
  59. }while(a < this.left.length);
  60. a -= this.left.length;
  61. this.splay(a);
  62. return a;
  63. }
  64. });
  65. return compression.Splay;
  66. });