forked from isysd/shallow-copy
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
James Halliday
committed
Jul 25, 2013
0 parents
commit 6831ce3
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]'; | ||
}; |