Skip to content

Commit

Permalink
length, clone, and copy
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Aug 27, 2010
1 parent df5b737 commit 249ec0f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
37 changes: 26 additions & 11 deletions lib/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,6 @@ module.exports = Hash;
var Traverse = require('traverse');

function Hash (hash, extra) {
if (extra == 'clone') { // deep copy
hash = Traverse.clone(hash);
}
else if (extra == 'copy') {
var acc = { __proto__ : hash.__proto__ };
Object.keys(hash).forEach(function (key) {
acc[key] = hash[key];
});
hash = acc;
}

var self = {
map : function (f) {
var acc = { __proto__ : hash.__proto__ };
Expand Down Expand Up @@ -75,9 +64,35 @@ function Hash (hash, extra) {
.map(function (key) { return hash[key] })
} });

Object.defineProperty(self, 'clone', { get : function () {
return Hash(Hash.clone(hash));
} });

Object.defineProperty(self, 'copy', { get : function () {
return Hash(Hash.copy(hash));
} });

Object.defineProperty(self, 'length', { get : function () {
return Object.keys(hash).length;
} });

return self;
};

// deep copy
Hash.clone = function (ref) {
return Traverse.clone(ref);
};

// shallow copy
Hash.copy = function (ref) {
var hash = { __proto__ : ref.__proto__ };
Object.keys(ref).forEach(function (key) {
hash[key] = ref[key];
});
return hash;
};

Hash.map = function (ref, f) {
return Hash(ref).map(f).items;
};
Expand Down
4 changes: 3 additions & 1 deletion test/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ exports['hash traversal'] = function (assert) {
assert.equal(hash1.b, 3);

var ref2 = { foo : [1,2], bar : [4,5] };
var hash2 = Hash.map(ref2, function (v) { v.unshift(v[0] - 1); return v });
var hash2 = Hash(ref2).clone.map(
function (v) { v.unshift(v[0] - 1); return v }
).items;
assert.equal(ref2.foo.join(' '), '1 2');
assert.equal(ref2.bar.join(' '), '4 5');
assert.equal(hash2.foo.join(' '), '0 1 2');
Expand Down

0 comments on commit 249ec0f

Please sign in to comment.