splay.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. if (!dojo._hasResource["dojox.encoding.splay"]) { // _hasResource checks added
  2. // by build. Do not use
  3. // _hasResource directly in
  4. // your code.
  5. dojo._hasResource["dojox.encoding.splay"] = true;
  6. dojo.provide("dojox.encoding.splay");
  7. dojox.encoding.Splay = function(n) {
  8. this.up = new Array(2 * n + 1);
  9. this.left = new Array(n);
  10. this.right = new Array(n);
  11. this.reset();
  12. };
  13. dojo.extend(dojox.encoding.Splay, {
  14. reset : function() {
  15. for (var i = 1; i < this.up.length; this.up[i] = Math.floor((i - 1)
  16. / 2), ++i);
  17. for (var i = 0; i < this.left.length; this.left[i] = 2 * i + 1, this.right[i] = 2
  18. * 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) {
  53. stream.putBits(s.pop() ? 1 : 0, 1);
  54. }
  55. return l;
  56. },
  57. decode : function(stream) {
  58. var a = 0; // root;
  59. do {
  60. a = this[stream.getBits(1) ? "right" : "left"][a];
  61. } while (a < this.left.length);
  62. a -= this.left.length;
  63. this.splay(a);
  64. return a;
  65. }
  66. });
  67. }