SoFunction
Updated on 2025-04-14

Prototype Hash Object Learning


//Hash object tool function
function $H(object) {
return new Hash(object);
};

var Hash = (Enumerable, (function() {

//Initialize, create a new Hash object
function initialize(object) {
this._object = (object) ? () : (object);
}

//Overwrite the methods in Enumerable and use them when traversing Hash objects
function _each(iterator) {
for (var key in this._object) {
var value = this._object[key], pair = [key, value];
= key;
= value;
iterator(pair);
}
}

function set(key, value) {
return this._object[key] = value;
}

function get(key) {
if (this._object[key] !== [key])
return this._object[key];
}

function unset(key) {
var value = this._object[key];
delete this._object[key];
return value;
}

function toObject() {
return (this._object);
}

function keys() {
return ('key');
}

function values() {
return ('value');
}

//Return the value key
function index(value) {
var match = (function(pair) {
return === value;
});
return match && ;
}

function merge(object) {
return ().update(object);
}

//Update the original Hash object and update the key-value pairs in the object parameter to the original Hash object
function update(object) {
return new Hash(object).inject(this, function(result, pair) {
(, );
return result;
});
}

function toQueryPair(key, value) {
if ((value)) return key;
return key + '=' + encodeURIComponent((value));
}

function toQueryString() {
return ([], function(results, pair) {
var key = encodeURIComponent(), values = ;

if (values && typeof values == 'object') {
if ((values))
return (((key)));
} else (toQueryPair(key, values));
return results;
}).join('&');
}

function inspect() {
return '#<Hash:{' + (function(pair) {
return ().join(': ');
}).join(', ') + '}>';
}

function toJSON() {
return (());
}

function clone() {
return new Hash(this);
}

return {
initialize: initialize,
_each: _each,
set: set,
get: get,
unset: unset,
toObject: toObject,
toTemplateReplacements: toObject,
keys: keys,
values: values,
index: index,
merge: merge,
update: update,
toQueryString: toQueryString,
inspect: inspect,
toJSON: toJSON,
clone: clone
};
})());

= $H;