├── .editorconfig ├── .eslintrc.json ├── .gitattributes ├── .gitignore ├── .travis.yml ├── .verb.md ├── LICENSE ├── README.md ├── fixtures └── app.js ├── index.js ├── package.json └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | indent_size = 2 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [{**/{actual,fixtures,expected,templates}/**,*.md}] 12 | trim_trailing_whitespace = false 13 | insert_final_newline = false -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": false, 4 | "es6": true, 5 | "node": true, 6 | "mocha": true 7 | }, 8 | 9 | "globals": { 10 | "document": false, 11 | "navigator": false, 12 | "window": false 13 | }, 14 | 15 | "rules": { 16 | "accessor-pairs": 2, 17 | "arrow-spacing": [2, { "before": true, "after": true }], 18 | "block-spacing": [2, "always"], 19 | "brace-style": [2, "1tbs", { "allowSingleLine": true }], 20 | "comma-dangle": [2, "never"], 21 | "comma-spacing": [2, { "before": false, "after": true }], 22 | "comma-style": [2, "last"], 23 | "constructor-super": 2, 24 | "curly": [2, "multi-line"], 25 | "dot-location": [2, "property"], 26 | "eol-last": 2, 27 | "eqeqeq": [2, "allow-null"], 28 | "generator-star-spacing": [2, { "before": true, "after": true }], 29 | "handle-callback-err": [2, "^(err|error)$" ], 30 | "indent": [2, 2, { "SwitchCase": 1 }], 31 | "key-spacing": [2, { "beforeColon": false, "afterColon": true }], 32 | "keyword-spacing": [2, { "before": true, "after": true }], 33 | "new-cap": [2, { "newIsCap": true, "capIsNew": false }], 34 | "new-parens": 2, 35 | "no-array-constructor": 2, 36 | "no-caller": 2, 37 | "no-class-assign": 2, 38 | "no-cond-assign": 2, 39 | "no-const-assign": 2, 40 | "no-control-regex": 2, 41 | "no-debugger": 2, 42 | "no-delete-var": 2, 43 | "no-dupe-args": 2, 44 | "no-dupe-class-members": 2, 45 | "no-dupe-keys": 2, 46 | "no-duplicate-case": 2, 47 | "no-empty-character-class": 2, 48 | "no-eval": 2, 49 | "no-ex-assign": 2, 50 | "no-extend-native": 2, 51 | "no-extra-bind": 2, 52 | "no-extra-boolean-cast": 2, 53 | "no-extra-parens": [2, "functions"], 54 | "no-fallthrough": 2, 55 | "no-floating-decimal": 2, 56 | "no-func-assign": 2, 57 | "no-implied-eval": 2, 58 | "no-inner-declarations": [2, "functions"], 59 | "no-invalid-regexp": 2, 60 | "no-irregular-whitespace": 2, 61 | "no-iterator": 2, 62 | "no-label-var": 2, 63 | "no-labels": 2, 64 | "no-lone-blocks": 2, 65 | "no-mixed-spaces-and-tabs": 2, 66 | "no-multi-spaces": 2, 67 | "no-multi-str": 2, 68 | "no-multiple-empty-lines": [2, { "max": 1 }], 69 | "no-native-reassign": 0, 70 | "no-negated-in-lhs": 2, 71 | "no-new": 2, 72 | "no-new-func": 2, 73 | "no-new-object": 2, 74 | "no-new-require": 2, 75 | "no-new-wrappers": 2, 76 | "no-obj-calls": 2, 77 | "no-octal": 2, 78 | "no-octal-escape": 2, 79 | "no-proto": 0, 80 | "no-redeclare": 2, 81 | "no-regex-spaces": 2, 82 | "no-return-assign": 2, 83 | "no-self-compare": 2, 84 | "no-sequences": 2, 85 | "no-shadow-restricted-names": 2, 86 | "no-spaced-func": 2, 87 | "no-sparse-arrays": 2, 88 | "no-this-before-super": 2, 89 | "no-throw-literal": 2, 90 | "no-trailing-spaces": 0, 91 | "no-undef": 2, 92 | "no-undef-init": 2, 93 | "no-unexpected-multiline": 2, 94 | "no-unneeded-ternary": [2, { "defaultAssignment": false }], 95 | "no-unreachable": 2, 96 | "no-unused-vars": [2, { "vars": "all", "args": "none" }], 97 | "no-useless-call": 0, 98 | "no-with": 2, 99 | "one-var": [0, { "initialized": "never" }], 100 | "operator-linebreak": [0, "after", { "overrides": { "?": "before", ":": "before" } }], 101 | "padded-blocks": [0, "never"], 102 | "quotes": [2, "single", "avoid-escape"], 103 | "radix": 2, 104 | "semi": [2, "always"], 105 | "semi-spacing": [2, { "before": false, "after": true }], 106 | "space-before-blocks": [2, "always"], 107 | "space-before-function-paren": [2, "never"], 108 | "space-in-parens": [2, "never"], 109 | "space-infix-ops": 2, 110 | "space-unary-ops": [2, { "words": true, "nonwords": false }], 111 | "spaced-comment": [0, "always", { "markers": ["global", "globals", "eslint", "eslint-disable", "*package", "!", ","] }], 112 | "use-isnan": 2, 113 | "valid-typeof": 2, 114 | "wrap-iife": [2, "any"], 115 | "yoda": [2, "never"] 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Enforce Unix newlines 2 | * text eol=lf 3 | 4 | # binaries 5 | *.ai binary 6 | *.psd binary 7 | *.jpg binary 8 | *.gif binary 9 | *.png binary 10 | *.jpeg binary 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # always ignore files 2 | *.DS_Store 3 | *.sublime-* 4 | 5 | # test related, or directories generated by tests 6 | test/actual 7 | actual 8 | coverage 9 | .nyc* 10 | 11 | # npm 12 | node_modules 13 | npm-debug.log 14 | 15 | # yarn 16 | yarn.lock 17 | yarn-error.log 18 | 19 | # misc 20 | _gh_pages 21 | _draft 22 | _drafts 23 | bower_components 24 | vendor 25 | temp 26 | tmp 27 | TODO.md 28 | package-lock.json -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | os: 3 | - linux 4 | - osx 5 | language: node_js 6 | node_js: 7 | - node 8 | - '8' 9 | - '7' 10 | - '6' 11 | - '5' 12 | - '4' 13 | - '0.12' 14 | - '0.10' 15 | -------------------------------------------------------------------------------- /.verb.md: -------------------------------------------------------------------------------- 1 | ## Usage 2 | 3 | ```js 4 | var copy = require('{%= name %}'); 5 | ``` 6 | 7 | ## API 8 | {%= apidocs("index.js") %} 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016-2017, Jon Schlinkert 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # object-copy [![NPM version](https://img.shields.io/npm/v/object-copy.svg?style=flat)](https://www.npmjs.com/package/object-copy) [![NPM monthly downloads](https://img.shields.io/npm/dm/object-copy.svg?style=flat)](https://npmjs.org/package/object-copy) [![NPM total downloads](https://img.shields.io/npm/dt/object-copy.svg?style=flat)](https://npmjs.org/package/object-copy) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/object-copy.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/object-copy) 2 | 3 | > Copy static properties, prototype properties, and descriptors from one object to another. 4 | 5 | ## Install 6 | 7 | Install with [npm](https://www.npmjs.com/): 8 | 9 | ```sh 10 | $ npm install --save object-copy 11 | ``` 12 | 13 | ## Usage 14 | 15 | ```js 16 | var copy = require('object-copy'); 17 | ``` 18 | 19 | ## API 20 | 21 | ### [copy](index.js#L32) 22 | 23 | Copy static properties, prototype properties, and descriptors from one object to another. 24 | 25 | **Params** 26 | 27 | * `receiver` **{Object}** 28 | * `provider` **{Object}** 29 | * `omit` **{String|Array}**: (optional) One or more properties to omit 30 | * `filter` **{Function}**: (optional) Called on each key before copying the property. If the function returns false, the property will not be copied. 31 | * `returns` **{Object}** 32 | 33 | **Example** 34 | 35 | ```js 36 | function App() {} 37 | var proto = App.prototype; 38 | App.prototype.set = function() {}; 39 | App.prototype.get = function() {}; 40 | 41 | var obj = {}; 42 | copy(obj, proto); 43 | 44 | // filter out keys 45 | copy(obj, proto, function(key) { 46 | return key !== 'index'; 47 | }); 48 | ``` 49 | 50 | ## About 51 | 52 | ### Related projects 53 | 54 | * [copy-descriptor](https://www.npmjs.com/package/copy-descriptor): Copy a descriptor from object A to object B | [homepage](https://github.com/jonschlinkert/copy-descriptor "Copy a descriptor from object A to object B") 55 | * [define-property](https://www.npmjs.com/package/define-property): Define a non-enumerable property on an object. | [homepage](https://github.com/jonschlinkert/define-property "Define a non-enumerable property on an object.") 56 | * [kind-of](https://www.npmjs.com/package/kind-of): Get the native type of a value. | [homepage](https://github.com/jonschlinkert/kind-of "Get the native type of a value.") 57 | 58 | ### Contributing 59 | 60 | Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). 61 | 62 | ### Building docs 63 | 64 | _(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ 65 | 66 | To generate the readme, run the following command: 67 | 68 | ```sh 69 | $ npm install -g verbose/verb#dev verb-generate-readme && verb 70 | ``` 71 | 72 | ### Running tests 73 | 74 | Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: 75 | 76 | ```sh 77 | $ npm install && npm test 78 | ``` 79 | 80 | ### Author 81 | 82 | **Jon Schlinkert** 83 | 84 | * [github/jonschlinkert](https://github.com/jonschlinkert) 85 | * [twitter/jonschlinkert](https://twitter.com/jonschlinkert) 86 | 87 | ### License 88 | 89 | Copyright © 2017, [Jon Schlinkert](https://github.com/jonschlinkert). 90 | Released under the [MIT License](LICENSE). 91 | 92 | *** 93 | 94 | _This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on June 25, 2017._ -------------------------------------------------------------------------------- /fixtures/app.js: -------------------------------------------------------------------------------- 1 | function App(options) { 2 | this.options = options || {}; 3 | } 4 | App.prototype.set = function(key, value) { 5 | this[key] = value; 6 | return this; 7 | }; 8 | App.prototype.get = function(key) { 9 | return this[key]; 10 | }; 11 | App.prototype.del = function(key) { 12 | delete this[key]; 13 | }; 14 | Object.defineProperty(App.prototype, 'count', { 15 | get: function () { 16 | return Object.keys(this).length; 17 | }, 18 | set: function () { 19 | } 20 | }); 21 | 22 | module.exports = App; -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var typeOf = require('kind-of'); 4 | var copyDescriptor = require('copy-descriptor'); 5 | var define = require('define-property'); 6 | 7 | /** 8 | * Copy static properties, prototype properties, and descriptors from one object to another. 9 | * 10 | * ```js 11 | * function App() {} 12 | * var proto = App.prototype; 13 | * App.prototype.set = function() {}; 14 | * App.prototype.get = function() {}; 15 | * 16 | * var obj = {}; 17 | * copy(obj, proto); 18 | * 19 | * // filter out keys 20 | * copy(obj, proto, function(key) { 21 | * return key !== 'index'; 22 | * }); 23 | * ``` 24 | * @param {Object} `receiver` 25 | * @param {Object} `provider` 26 | * @param {String|Array} `omit` (optional) One or more properties to omit 27 | * @param {Function} `filter` (optional) Called on each key before copying the property. If the function returns false, the property will not be copied. 28 | * @return {Object} 29 | * @api public 30 | */ 31 | 32 | function copy(receiver, provider, omit, fn) { 33 | if (!isObject(receiver)) { 34 | throw new TypeError('expected receiving object to be an object.'); 35 | } 36 | if (!isObject(provider)) { 37 | throw new TypeError('expected providing object to be an object.'); 38 | } 39 | 40 | if (typeof omit === 'function') { 41 | fn = omit; 42 | omit = []; 43 | } 44 | 45 | var props = nativeKeys(provider); 46 | var keys = Object.keys(provider); 47 | var len = props.length; 48 | omit = arrayify(omit); 49 | 50 | while (len--) { 51 | var key = props[len]; 52 | if (typeof fn === 'function' && fn(key) === false) { 53 | continue; 54 | } 55 | 56 | if (has(keys, key)) { 57 | define(receiver, key, provider[key]); 58 | } else if (!(key in receiver) && !has(omit, key)) { 59 | copyDescriptor(receiver, provider, key); 60 | } 61 | } 62 | }; 63 | 64 | /** 65 | * Return true if the given value is an object or function 66 | */ 67 | 68 | function isObject(val) { 69 | return typeOf(val) === 'object' || typeof val === 'function'; 70 | } 71 | 72 | /** 73 | * Returns true if an array has any of the given elements, or an 74 | * object has any of the given keys. 75 | * 76 | * ```js 77 | * has(['a', 'b', 'c'], 'c'); 78 | * //=> true 79 | * 80 | * has(['a', 'b', 'c'], ['c', 'z']); 81 | * //=> true 82 | * 83 | * has({a: 'b', c: 'd'}, ['c', 'z']); 84 | * //=> true 85 | * ``` 86 | * @param {Object} `obj` 87 | * @param {String|Array} `val` 88 | * @return {Boolean} 89 | */ 90 | 91 | function has(obj, val) { 92 | val = arrayify(val); 93 | var len = val.length; 94 | 95 | if (isObject(obj)) { 96 | for (var key in obj) { 97 | if (val.indexOf(key) > -1) { 98 | return true; 99 | } 100 | } 101 | 102 | var keys = nativeKeys(obj); 103 | return has(keys, val); 104 | } 105 | 106 | if (Array.isArray(obj)) { 107 | var arr = obj; 108 | while (len--) { 109 | if (arr.indexOf(val[len]) > -1) { 110 | return true; 111 | } 112 | } 113 | return false; 114 | } 115 | 116 | throw new TypeError('expected an array or object.'); 117 | } 118 | 119 | /** 120 | * Cast the given value to an array. 121 | * 122 | * ```js 123 | * arrayify('foo'); 124 | * //=> ['foo'] 125 | * 126 | * arrayify(['foo']); 127 | * //=> ['foo'] 128 | * ``` 129 | * 130 | * @param {String|Array} `val` 131 | * @return {Array} 132 | */ 133 | 134 | function arrayify(val) { 135 | return val ? (Array.isArray(val) ? val : [val]) : []; 136 | } 137 | 138 | /** 139 | * Returns true if a value has a `contructor` 140 | * 141 | * ```js 142 | * hasConstructor({}); 143 | * //=> true 144 | * 145 | * hasConstructor(Object.create(null)); 146 | * //=> false 147 | * ``` 148 | * @param {Object} `value` 149 | * @return {Boolean} 150 | */ 151 | 152 | function hasConstructor(val) { 153 | return isObject(val) && typeof val.constructor !== 'undefined'; 154 | } 155 | 156 | /** 157 | * Get the native `ownPropertyNames` from the constructor of the 158 | * given `object`. An empty array is returned if the object does 159 | * not have a constructor. 160 | * 161 | * ```js 162 | * nativeKeys({a: 'b', b: 'c', c: 'd'}) 163 | * //=> ['a', 'b', 'c'] 164 | * 165 | * nativeKeys(function(){}) 166 | * //=> ['length', 'caller'] 167 | * ``` 168 | * 169 | * @param {Object} `obj` Object that has a `constructor`. 170 | * @return {Array} Array of keys. 171 | */ 172 | 173 | function nativeKeys(val) { 174 | if (!hasConstructor(val)) return []; 175 | return Object.getOwnPropertyNames(val); 176 | } 177 | 178 | /** 179 | * Expose `copy` 180 | */ 181 | 182 | module.exports = copy; 183 | 184 | /** 185 | * Expose `copy.has` for tests 186 | */ 187 | 188 | module.exports.has = has; 189 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "object-copy", 3 | "description": "Copy static properties, prototype properties, and descriptors from one object to another.", 4 | "version": "1.0.0", 5 | "homepage": "https://github.com/jonschlinkert/object-copy", 6 | "author": "Jon Schlinkert (https://github.com/jonschlinkert)", 7 | "repository": "jonschlinkert/object-copy", 8 | "bugs": { 9 | "url": "https://github.com/jonschlinkert/object-copy/issues" 10 | }, 11 | "license": "MIT", 12 | "files": [ 13 | "index.js" 14 | ], 15 | "main": "index.js", 16 | "engines": { 17 | "node": ">=0.10.0" 18 | }, 19 | "scripts": { 20 | "test": "mocha" 21 | }, 22 | "dependencies": { 23 | "copy-descriptor": "^0.1.1", 24 | "define-property": "^1.0.0", 25 | "kind-of": "^5.0.0" 26 | }, 27 | "devDependencies": { 28 | "gulp-format-md": "^0.1.12", 29 | "mocha": "^3.4.2" 30 | }, 31 | "keywords": [ 32 | "copy", 33 | "object" 34 | ], 35 | "verb": { 36 | "layout": "default", 37 | "plugins": [ 38 | "gulp-format-md" 39 | ], 40 | "related": { 41 | "list": [ 42 | "copy-descriptor", 43 | "define-property", 44 | "kind-of" 45 | ] 46 | }, 47 | "reflinks": [ 48 | "verb" 49 | ] 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | require('mocha'); 4 | var assert = require('assert'); 5 | var App = require('./fixtures/app'); 6 | var copy = require('./'); 7 | 8 | describe('object-copy', function() { 9 | it('should export a function', function() { 10 | assert.equal(typeof copy, 'function'); 11 | }); 12 | 13 | it('should copy a descriptor from the provider to receiver:', function() { 14 | var proto = App.prototype; 15 | var obj = {}; 16 | copy(obj, proto, 'count'); 17 | assert(!('count' in obj)); 18 | assert('get' in obj); 19 | assert('set' in obj); 20 | }); 21 | 22 | it('should do nothing when the descriptor does not exist:', function() { 23 | var proto = App.prototype; 24 | var obj = {}; 25 | copy(obj, proto, 'foo'); 26 | assert.deepEqual(obj, {}); 27 | }); 28 | 29 | it('should throw an error when receiver is not an object:', function(cb) { 30 | try { 31 | copy('foo'); 32 | cb(new Error('expected an error')); 33 | } catch (err) { 34 | assert.equal(err.message, 'expected receiving object to be an object.'); 35 | cb(); 36 | } 37 | }); 38 | 39 | it('should throw an error when provider is not an object:', function(cb) { 40 | try { 41 | copy({}, 'foo'); 42 | cb(new Error('expected an error')); 43 | } catch (err) { 44 | assert.equal(err.message, 'expected providing object to be an object.'); 45 | cb(); 46 | } 47 | }); 48 | }); 49 | --------------------------------------------------------------------------------