prototype/src/hash.js

102 lines
2.4 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() {
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) {
2007-10-14 08:08:42 +00:00
this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
2007-10-13 10:55:52 +00:00
},
_each: function(iterator) {
for (var key in this._object) {
var value = this._object[key], pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},
2007-10-13 10:55:52 +00:00
set: function(key, value) {
return this._object[key] = value;
},
get: function(key) {
// simulating poorly supported hasOwnProperty
if (this._object[key] !== Object.prototype[key])
return this._object[key];
2007-10-13 10:55:52 +00:00
},
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.inject([], function(results, pair) {
2007-10-13 10:55:52 +00:00
var key = encodeURIComponent(pair.key), values = pair.value;
if (values && typeof values == 'object') {
if (Object.isArray(values))
return results.concat(values.map(toQueryPair.curry(key)));
} else results.push(toQueryPair(key, values));
return results;
2007-10-13 10:55:52 +00:00
}).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.prototype.toTemplateReplacements = Hash.prototype.toObject;
Hash.from = $H;