119 lines
2.7 KiB
JavaScript
119 lines
2.7 KiB
JavaScript
function $H(object) {
|
|
return new Hash(object);
|
|
};
|
|
|
|
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);
|
|
}
|
|
}
|
|
} 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);
|
|
}
|
|
}
|
|
}
|
|
|
|
function toQueryPair(key, value) {
|
|
if (Object.isUndefined(value)) return key;
|
|
return key + '=' + encodeURIComponent(String.interpret(value));
|
|
}
|
|
|
|
return {
|
|
initialize: function(object) {
|
|
this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
|
|
},
|
|
|
|
_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);
|
|
}
|
|
}
|
|
})());
|
|
|
|
Hash.from = $H; |