[whatwg] Sample DOMTokenString Implementation

Erik Arvidsson erik at eae.net
Tue Sep 6 16:15:54 PDT 2005


You can get has(token) to be constant, O(1), by using a hash here. add 
and remove will remain linear as long as a copy is required.

You are really misusing new here. You never return an object of type 
DOMTokenString. Since all your methods are linear and return a new 
string you might as well implement them on the String prototype object.

String.prototype.has = function (s) {
    // TODO: Needs to validate s
    return RegExp("(^|\\s+)" + s + "(\\s+|$)", "g").test(this);
};

String.prototype.add = function (s) {
    // TODO: Needs to validate s
    //       This should check that we don't have this token already
    return this + " " + s;
};

String.prototype.remove = function (s) {
    // TODO: Needs to validate s
    return this.replace(RegExp("(^|\\s+)" + s + "(\\s+|$)", "g"), "");
};

Now native strings in JS implement the DOMTokenString interface ;-)

If you want a mutable object then we cannot extend String (as you said).

Lachlan Hunt wrote:
>     s = s.add("foo"); // returns "foo bar foo"

This should not add another foo

>     s = s.add("baz quux") // returns "foo bar foo baz quux"

Shouldn't this raise an exception?


erik



More information about the whatwg mailing list