Friday, July 24, 2009

TurboStringMap for Gwt

In my previous post I did mention that Gwt has the basic Java collections emulated in Javascript. In the browser such rich interfaces may not be needed. There is a lightweight Map implementation where the keys are constrained to String types only called FastStringMap. It is directly backed by a Js array. Want to go even lighter then here is the derived TurboStringMap which even a thinner API over a Js array to act like a Map.

The rest of the this post is Gwt Java code-


package com.onyem.finance.client;

import com.google.gwt.core.client.JavaScriptObject;

class TurboStringMap {

/*
* Accesses need to be prefixed with ':' to prevent conflict with built-in
* JavaScript properties.
*/
@SuppressWarnings("unused")
private JavaScriptObject map;

public TurboStringMap() {
init();
}

public void clear() {
init();
}

private native void init() /*-{
this.@com.onyem.finance.client.TurboStringMap::map = {};
}-*/;

// Prepend ':' to avoid conflicts with built-in Object properties.
public native T get(String key) /*-{
return this.@com.onyem.finance.client.TurboStringMap::map[':' + key];
}-*/;

// Prepend ':' to avoid conflicts with built-in Object properties.
public native T put(String key, T value) /*-{
key = ':' + key;
var map = this.@com.onyem.finance.client.TurboStringMap::map;
var previous = map[key];
map[key] = value;
return previous;
}-*/;

// Prepend ':' to avoid conflicts with built-in Object properties.
public native T remove(String key) /*-{
key = ':' + key;
var map = this.@com.onyem.finance.client.TurboStringMap::map;
var previous = map[key];
delete map[key];
return previous;
}-*/;

// only count keys with ':' prefix
public native int size() /*-{
var value = this.@com.onyem.finance.client.TurboStringMap::map;
var count = 0;
for(var key in value) {
if (key.charAt(0) == ':') ++count;
}
return count;
}-*/;

public boolean isEmpty() {
return size() == 0;
}

public native String[] keys() /*-{
var value = this.@com.onyem.finance.client.TurboStringMap::map;
var keys = [];
for(var key in value) {
keys.push(key.substring(1));
}
return keys;
}-*/;
}

No comments: