prototype/src/hash.js

119 lines
2.7 KiB
JavaScript
Raw Normal View History

2007-10-13 10:55:52 +00:00
function $H(object) {
return new Hash(object);
2007-01-18 22:24:27 +00:00
};
2007-10-13 10:55:52 +00:00
var Hash = Class.create(Enumerable, (function() {
if (function() {
var i = 0, Test = function(value) { this.key = value };
Test.prototype.key = 'foo';
for (var property in new Test('bar')) i++;
return i > 1;
}()) {
function each(iterator) {
var cache = [];
for (var key in this._object) {
var value = this._object[key];
if (cache.include(key)) continue;
cache.push(key);
var pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
2007-01-18 22:24:27 +00:00
}
}
2007-10-13 10:55:52 +00:00
} else {
function each(iterator) {
for (var key in this._object) {
var value = this._object[key], pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
2007-01-18 22:24:27 +00:00
}
}
2007-10-13 10:55:52 +00:00
}
2007-10-13 10:55:52 +00:00
function toQueryPair(key, value) {
if (Object.isUndefined(value)) return key;
return key + '=' + encodeURIComponent(String.interpret(value));
2007-01-18 22:24:27 +00:00
}
2007-10-13 10:55:52 +00:00
return {
initialize: function(object) {
this._object = object instanceof Hash ? object.toObject() : Object.clone(object);
},
2007-10-13 10:55:52 +00:00
_each: each,
set: function(key, value) {
return this._object[key] = value;
},
get: function(key) {
return this._object[key];
},
unset: function(key) {
var value = this._object[key];
delete this._object[key];
return value;
},
toObject: function() {
return Object.clone(this._object);
},
keys: function() {
return this.pluck('key');
},
values: function() {
return this.pluck('value');
},
index: function(value) {
var match = this.detect(function(pair) {
return pair.value === value;
});
return match && match.key;
},
merge: function(object) {
return this.clone().update(object);
},
update: function(object) {
return new Hash(object).inject(this, function(result, pair) {
result.set(pair.key, pair.value);
return result;
});
},
toQueryString: function() {
return this.map(function(pair) {
var key = encodeURIComponent(pair.key), values = pair.value;
if (values && typeof values == 'object') {
if (Object.isArray(values))
return values.map(toQueryPair.curry(key)).join('&');
}
return toQueryPair(key, values);
}).join('&');
},
inspect: function() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
},
toJSON: function() {
return Object.toJSON(this.toObject());
},
clone: function() {
return new Hash(this);
}
}
2007-10-13 10:55:52 +00:00
})());
Hash.from = $H;