Skip to content

Commit

Permalink
working example
Browse files Browse the repository at this point in the history
  • Loading branch information
James Halliday committed Jul 25, 2013
0 parents commit 6831ce3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
8 changes: 8 additions & 0 deletions example/copy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
var copy = require('../');

var obj = { a: 3, b: 4, c: 5 };
var dup = copy(obj);
dup.b *= 111;

console.log('original: ', obj);
console.log('copy: ', dup);
35 changes: 35 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
module.exports = function (obj) {
if (!obj || typeof obj !== 'object') return obj;

var copy;

if (isArray(obj)) {
var len = obj.length;
copy = Array(len);
for (var i = 0; i < len; i++) {
copy[i] = obj[i];
}
}
else {
var keys = objectKeys(obj);
copy = {};

for (var i = 0, l = keys.length; i < l; i++) {
var key = keys[i];
copy[key] = obj[key];
}
}
return copy;
};

var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in keys) {
if ({}.hasOwnProperty.call(obj, key)) keys.push(key);
}
return keys;
};

var isArray = Array.isArray || function (xs) {
return {}.toString.call(xs) === '[object Array]';
};

0 comments on commit 6831ce3

Please sign in to comment.