prototype/src/hash.js

113 lines
2.7 KiB
JavaScript
Raw Normal View History

var Hash = function(object) {
if (object instanceof Hash) this.merge(object);
else Object.extend(this, object || {});
2007-01-18 22:24:27 +00:00
};
Object.extend(Hash, {
toQueryString: function(obj) {
var parts = [];
parts.add = arguments.callee.addPair;
2007-01-18 22:24:27 +00:00
this.prototype._each.call(obj, function(pair) {
2007-01-18 22:24:27 +00:00
if (!pair.key) return;
var value = pair.value;
2007-01-18 22:24:27 +00:00
if (value && typeof value == 'object') {
if (value.constructor == Array) value.each(function(value) {
parts.add(pair.key, value);
});
return;
2007-01-18 22:24:27 +00:00
}
parts.add(pair.key, value);
});
2007-01-18 22:24:27 +00:00
return parts.join('&');
}
});
Hash.toQueryString.addPair = function(key, value, prefix) {
if (value == null) return;
key = encodeURIComponent(key);
this.push(key + '=' + (value == null ? '' : encodeURIComponent(value)));
}
2007-01-18 22:24:27 +00:00
Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
_each: function(iterator) {
for (var key in this) {
var value = this[key];
if (value && value == Hash.prototype[key]) continue;
var pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
},
keys: function() {
return this.pluck('key');
},
values: function() {
return this.pluck('value');
},
merge: function(hash) {
return $H(hash).inject(this, function(mergedHash, pair) {
mergedHash[pair.key] = pair.value;
return mergedHash;
});
},
remove: function() {
var result;
for(var i = 0, length = arguments.length; i < length; i++) {
var value = this[arguments[i]];
if (value !== undefined){
if (result === undefined) result = value;
else {
if (result.constructor != Array) result = [result];
result.push(value)
}
}
delete this[arguments[i]];
}
return result;
},
toQueryString: function() {
return Hash.toQueryString(this);
},
inspect: function() {
return '#<Hash:{' + this.map(function(pair) {
return pair.map(Object.inspect).join(': ');
}).join(', ') + '}>';
}
});
function $H(object) {
if (object instanceof Hash) return object;
2007-01-18 22:24:27 +00:00
return new Hash(object);
};
// Safari iterates over shadowed properties
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;
}()) Hash.prototype._each = function(iterator) {
var cache = [];
for (var key in this) {
var value = this[key];
if ((value && value == Hash.prototype[key]) || cache.include(key)) continue;
cache.push(key);
var pair = [key, value];
pair.key = key;
pair.value = value;
iterator(pair);
}
};