[whatwg] Sample DOMTokenString Implementation

Hi,
   I implemented a sample DOMTokenString() interface tonight [1].

Since String() is immutable in JS, I couldn't implement it as suggested 
in the current draft.  So, instead, I've implemented it like this:

interface DOMTokenString : DOMString {
     bool            has(in DOMString token);
     DOMTokenString  add(in DOMString token);
     DOMTokenString  remove(in DOMString token);
}

The constructor accepts a single string as a parameter

     new DOMTokenString(string);

The string is split into tokens and stored in an private array within 
the object:
     var tokens = string.split(/\s/);

That splits it on any whitespace characters.  The tokens are then 
rejoined into a string using a single space as the separator.  This is 
similar to the way class works in HTML (at least, in Gecko).

i.e. class="foo bar" is equivalent to class=" foo   bar ", and in Gecko, 
.className returns each separated by a single space.

     e.g.
     var s = new DOMTokenString(" foo   bar "); // returns "foo bar"

bool has();

   * This searches the array for the first index of the specified token
     and returns true if found, false otherwise.
     e.g.

     s.has("bar"); // returns true;
     s.has ("foo bar") // returns false;

DOMTokenString add();

   * This function returns a new DOMTokenString() created from the
     concatenation of the the current string(), a separator and the new
     token.
   * It does not matter if the same token is already present, the new
     token is just appended to the end.
   * If the token parameter is, itself, a space separated list, it is
     (because of the way the new string is constructed) equivalent to
     adding each token individually.

     e.g.
     s = s.add("foo"); // returns "foo bar foo"
     s = s.add("baz quux") // returns "foo bar foo baz quux"

DOMTokenString remove();

   * This filters the tokens array, removing all occurances of matching
     tokens.  The new token array is then joined and returned.

     e.g.
     s = s.remove("foo") // returns "bar baz quux"
     s = s.remove("bar baz") // returns "bar baz quux" (i.e. no match)
     s = s.remove("baz"); // returns "bar quux"

[1] http://lachy.id.au/dev/script/examples/DOM/DOMTokenString.js

-- 
Lachlan Hunt
http://lachy.id.au/

Received on Tuesday, 6 September 2005 06:11:22 UTC