Code Monkey home page Code Monkey logo

clone's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

clone's Issues

arrays are cloned incorrectly

Try these examples

abc = {
  arr1: [
    {
      a: '1234',
      b: '2345'
    }
  ],
  arr2: [
    {
      c: '345',
      d: '456'
    }
  ]
};
log(abc);
abc2 = clone(abc);
log(abc2);
log(_(abc).isEqual(abc2)); // false

log(abc) returns

{ arr1: [ { a: '1234', b: '2345' } ],
  arr2: [ { c: '345', d: '456' } ] }

log(abc2) returns

{ arr1: { '0': { a: '1234', b: '2345' } },
  arr2: { '0': { c: '345', d: '456' } } }

Maybe you can incorporate this code http://coffeescriptcookbook.com/chapters/classes_and_objects/cloning

License

Hi,

I'm currently creating an RPM for Enterprise Linux. Is it possible to change the license type to MIT, ISC or BSD? It will create a more flexible use, IMO. Thanks for letting me know. For more details, read this thread:
https://www.axivo.com/threads/ghost-setup.68/

ES5 property attributes are not preserved

Consider the following example:

var o = {};
Object.defineProperty(o, 'foo', {enumerable:true, writable:false, value:'f'});
var o2 = clone(o);

console.log(Object.getOwnPropertyDescriptor(o2, 'foo'));

The property descriptor on the copied object specifies the property as writable even though the original property wasn't writable.

Getter value copied in to clone

Rather than coping the getter method to the clone, it looks like the result of the getter is copied in.

var test = {
  a: "world",
  get b(){ return "hello" + this.a; }
};
var cloned = clone(test);
console.log("Original: ", test);
console.log("Cloned: ", cloned);

Yields

Original:  { a: ' world', b: [Getter] }
Cloned:  { a: ' world', b: 'hello world' }

Child-object arrays return as objects when using clone

When cloning an objects child, where the child value is an array. Clone will always return the child array as an object.

var data = {
"note" : {
"topics" : ["topic 1","topic 2"]
}
};

var noteTopics = data.note.topics;
var tempNoteTopics = Clone(noteTopics);

// returns an object...
// {
// "0" : "topic 1",
// "1" : "topic 2"
// }

This should be an array.

Cloning a class that extends Map, e.g. a "DefaultMap", returns a Map instead

I have a custom class that extends from Map. This class is "DefaultMap", and provides a default value when an item is not found in the Map.

It looks like instances of "DefaultMap" are getting cloned as just "Map". It then loses the custom functionality provided by "DefaultMap".

Here's a test case in Mocha to reproduce the problem:

const assert = require('assert');
const clone = require('clone');

describe(`clone`, function () {
    it(`can deep copy a class that extends map`, function () {
        let overridingMethodWasCalled = false;
        class DefaultMap extends Map {
            constructor(defaultValueFactory, iterable) {
                super(iterable);
                this.defaultValueFactory = defaultValueFactory;
            }

            get(key) {
                overridingMethodWasCalled = true;
                if (!this.has(key)) {
                    const value = this.defaultValueFactory(key, this);
                    this.set(key, value);
                    return value;
                } else {
                    return super.get(key);
                }
            }
        }

        const defaultValue = 'placeholder';
        const map = new DefaultMap(() => defaultValue);
        const obj = {
            myMap: map
        };

        const copiedObj = clone(obj);
        console.log(obj, copiedObj);
        assert.notStrictEqual(obj.myMap, copiedObj.myMap, "Properties holding Maps should not reference the same object in memory");
        assert.strictEqual(obj.myMap.size, copiedObj.myMap.size, "The cloned Map should have the same size as the original Map");

        const value = copiedObj.myMap.get('nonExistentKey');
        assert.ok(overridingMethodWasCalled, "The overriding method on DefaultMap should be called");
        assert.strictEqual(value, defaultValue, "The cloned Map should be a DefaultMap, and should return the default value when given a non-existent key");
        assert.notStrictEqual(obj.myMap.size, copiedObj.myMap.size, "After implicitly inserting an element, the cloned Map should have a different size to the original Map");
    });
});

The test fails at the assertion "The overriding method on DefaultMap should be called".

Tested in clone v2.1.1, Node v6.9.1.

typed arrays are cloned incorrectly

require('clone')(new Float32Array([10,11]))

Float32Array { '0': 10, '1': 11 }  // actual
Float32Array [ 10, 11 ] // expected

Similar to #1, but for typed arrays.

node_object_wrap.h Assertion `handle->InternalFieldCount() > 0' failed.

I am using gulp-minify-css which uses this library. I've narrowed down an issue I'm getting after a recent update to clone. On clone v0.1.11 things run fine, but updating to 0.1.13 I get the following error:

gulp: ../src/node_object_wrap.h:61: static T* node::ObjectWrap::Unwrap(v8::Handle<v8::Object>) [with T = node::Buffer]: Assertion `handle->InternalFieldCount() > 0' failed.

I'm not sure what could be causing this or if this is the right place for the bug. My apologies if this isn't the correct project to report this bug.

$ node --version
v0.10.15 
# Also happens on v0.10.26

TypeError: Illegal invocation (in Chromium)

Unzip clone-issue.zip
and:

npm install
./node_modules/.bin/browserify test.js > bundle.js
chromium-browser test.html

Got:

bundle.js:2206 Uncaught TypeError: Illegal invocation

    at _clone (bundle.js:2206)
    at clone (bundle.js:2246)
    at Object.30.clone (bundle.js:3077)
    at o (bundle.js:1)
    at r (bundle.js:1)
    at bundle.js:1

npm - No README

The readme doesn't seem to make it to npm, which is inconvenient. Would be nice to see the contents there rather than having to come through to github.

getRegExpFlags still broken

The official version of 1.0.1 has the following:

if (global.TESTING) clone.getRegExpFlags = getRegExpFlags;
if (global.TESTING) clone.objectToString = objectToString;
if (global.TESTING) clone.isDate   = isDate;
if (global.TESTING) clone.isArray  = isArray;
if (global.TESTING) clone.isRegExp = isRegExp;

and there is still the crash from #41

I don't know what global.TESTING is for, but I think there is something wrong with it. Please can you fix?

clone(obj) removes property "Id"

given this object:
var x = {
"Desc" : "Lorem ipsum dolor...",
"Features" : [],
"Id" : "WC"
};

if you were to do:
var y = clone(x);
console.log(y);

you would get:
{
"Desc" : "Lorem ipsum dolor...",
"Features" : []
}

npm install node-clone gets the incorrect version?

Hi, I am installing node-clone through "npm install node-clone", but the clone.js I got has different content from the head version:

//Universal js Clone function (we think...)
//Works for any js object

var FN=function(fn) {
this.clone=fn;
};

exports.Clone=function(fn) {return new FN(fn).clone;};

Any idea what went wrong?

Overlapping inherited and own properties

"use strict";

var clone = require("clone");

function Foo() {}
Foo.prototype.prop = 1;

var a = new Foo;
a.prop = 2;

var b = clone(a);

console.log(a, b);

Hello,

please tell if this is a bug. When parent object has an own and an inherited property with the same name, then the cloned one will not have the own one copied. This works correct if we have only an own or only an inherited one on the parent.

clone seems to be appending data

The clone function is appending functions to my code. My code looks like this

console.log(script)
let input = clone(script)
console.log('----------------')
console.log(input)
process.exit(0)

and outputs this (this first data is the input, the data below ---------- is the output). The output
has list data (I think appended to it)

{ data: 
   [ { pattern: [Array],
       response: [Array],
       details: [Object],
       intent: [Array],
       phraseClass: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] } ] }
----------------
{ data: 
   [ { pattern: [Array],
       response: [Array],
       details: [Object],
       intent: [Array],
       phraseClass: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     { pattern: [Array], intent: [Array] },
     __class__: { [Function: list] __name__: 'list' },
     __iter__: [Function],
     __getslice__: [Function],
     __setslice__: [Function],
     __repr__: [Function],
     __str__: [Function],
     append: [Function],
     clear: [Function],
     extend: [Function],
     insert: [Function],
     remove: [Function],
     index: [Function],
     py_pop: [Function],
     py_sort: [Function],
     __add__: [Function],
     __mul__: [Function],
     __rmul__: [Function],
     __bindexOf__: [Function],
     add: [Function],
     discard: [Function],
     isdisjoint: [Function],
     issuperset: [Function],
     issubset: [Function],
     union: [Function],
     intersection: [Function],
     difference: [Function],
     symmetric_difference: [Function],
     py_update: [Function],
     __eq__: [Function],
     __ne__: [Function],
     __le__: [Function],
     __ge__: [Function],
     __lt__: [Function],
     __gt__: [Function] ] }

Is this the intended result? How do I get rid of the extra 'list' data?

use Object.create() ?

function cloneObject(source) {
    var key,value;
    var clone = Object.create(source);

    for (key in source) {
        if (source.hasOwnProperty(key) === true) {
            value = source[key];

            if (value!==null && typeof value==="object") {
                clone[key] = cloneObject(value);
            } else {
                clone[key] = value;
            }
        }
    }

    return clone;
}

Works with instanceof, has the prototype, and has enumerable keys.

Can not clone object with Symbol keys

Example:

const s = Symbol();
const a = {
  [s]: 'hello'
};
const b = clone(a);

console.log(a[s]); // => hello
console.log(b[s]); // => undefined

It's probably caused by the fact that Symbol properties are not enumerable as the normal property names. So, we don't get it by for (var i in parent) on line 90 of clone.js.

Circular References don't work

If you have circular references in your Objects, the stack blows up. I have an idea on how to support circular references. Would you accept a pull request?

It went wrong when clone an Error

const error = new Error('hhhhhh');
console.log(error);
/*
 Error: hhhhhh
 at Object.<anonymous> (/Users/miserylee/Documents/projects/com.whxxcy.8ddao/test.js:3:15)
 at Module._compile (module.js:541:32)
 at Object.Module._extensions..js (module.js:550:10)
 at Module.load (module.js:458:32)
 at tryModuleLoad (module.js:417:12)
 at Function.Module._load (module.js:409:3)
 at Module.runMain (module.js:575:10)
 at run (bootstrap_node.js:352:7)
 at startup (bootstrap_node.js:144:9)
 at bootstrap_node.js:467:3
 */
console.log(clone(error));
/*
 [Error]
 */

TypeError: The HTMLDivElement.align setter can only be used on instances of HTMLDivElement

When copying a DOM object, following line fails:

child[i] = _clone(parent[i], depth - 1);

clone/clone.js

Line 156 in e3f252d

child[i] = _clone(parent[i], depth - 1);

TypeError: The HTMLDivElement.align setter can only be used on instances of HTMLDivElement

It seems like calling Object.getPrototypeOf on a DOM element gives HTMLDivElementPrototype which has a slightly different behavior than HtmlDivElement.

Reproducible in Safari Version 10.0 (10602.1.50.0.10)

Error: Object.getPrototypeOf called on non-object

Getting this with the latest version of clone (0.3.13), in Mac OSX and Linux, running node 0.10.x.

I don't actually use clone, but dependencies on my project do - and it's breaking all the Travis builds.

Here's the specific stack-trace I get: http://d.pr/i/YBKP

Here's the line that calls clone in gulp-minify-css: https://github.com/jonathanepollack/gulp-minify-css/blob/master/index.js#L39

Let me know if there's anything I can do to help or to test.

Thanks.

It kills mongoose methods

When I try to use clone() to clone an mongoose array or mongoose object in my application,

when try to clone mongoose object...

/home/kitz/myProject/node_modules/mongoose/lib/types/embedded.js:65
    this.__parentArray._markModified();
                       ^
TypeError: undefined is not a function
    at EmbeddedDocument.markModified (/home/kitz/myProject/node_modules/mongoose/lib/types/embedded.js:65:24)
    at EmbeddedDocument.Document.$__set (/home/kitz/myProject/node_modules/mongoose/lib/document.js:665:10)
    at EmbeddedDocument.Document.set (/home/kitz/myProject/node_modules/mongoose/lib/document.js:603:10)
    at EmbeddedDocument.Object.defineProperty.set [as _id] (/home/kitz/myProject/node_modules/mongoose/lib/document.js:1421:45)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:16)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at clone (/home/kitz/myProject/node_modules/clone/clone.js:105:10)
    at Object.Util.clone (/home/kitz/myProject/libs/util.js:38:9)
    at model.SomeSchema.methods.someFunc (/home/kitz/myProject/models/some.js:238:23)
    at /home/kitz/myProject/models/some.js:418:22
    at /home/kitz/myProject/node_modules/mongoose/lib/query.js:1173:16

when try to clone mongoose array...

/home/kitz/myProject/node_modules/mongoose/lib/document.js:1153
  if (!this.$__.validationError) {
               ^
TypeError: Cannot read property 'validationError' of undefined
    at model.Document.invalidate (/home/kitz/myProject/node_modules/mongoose/lib/document.js:1153:16)
    at EmbeddedDocument.invalidate (/home/kitz/myProject/node_modules/mongoose/lib/types/embedded.js:177:19)
    at EmbeddedDocument.Document.set (/home/kitz/myProject/node_modules/mongoose/lib/document.js:597:10)
    at EmbeddedDocument.Object.defineProperty.set [as _id] (/home/kitz/myProject/node_modules/mongoose/lib/document.js:1421:45)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:16)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at _clone (/home/kitz/myProject/node_modules/clone/clone.js:99:18)
    at clone (/home/kitz/myProject/node_modules/clone/clone.js:105:10)
    at Object.Util.clone (/home/kitz/myProject/libs/util.js:29:9)
    at model.SomeSchema.methods.someFunc (/home/kitz/myProject/models/some.js:238:25)

Support for ES6 modules

Just a thought, support for ES6 modules could be added by adding one line to the last if block of clone.js like so:

if (typeof module === 'object' && module.exports) {
  module.exports = clone;
  module.exports.default = clone;
}

Support cloning of promises

Add support for Promises (Node 0.12+). Someting like:

if (typeof Promise === 'function' && value instanceof Promise) {
  clone = new Promise(function(fulfill, reject) {
    value.then(function(result) {
      fulfill(clone(result));
    }, function(reason) {
      reject(clone(reason));
    });
  });
}

What is the 1.x -> 2.x breaking change?

I see a major version change from 1.x -> 2.x. Assuming this repo follows semver semantics, what breaking change was introduced?

Thanks for your time on this project.

cloning File objects

  1. Take File object from <input type='file'>
  2. Try to clone
TypeError: Cannot assign to read only property 'size' of object '#<File>'
    at _clone (clone.js:156)
    at _clone (clone.js:156)
    at _clone (clone.js:156)
    at _clone (clone.js:156)
    at _clone (clone.js:156)
    at _clone (clone.js:156)
    at clone (clone.js:196)
    at LogEntry.set (LogEntry.js:148)

Regex cloning broken in 1.0.0

clone = require 'clone'
clone({regex: /^hello/})

TypeError: Object function clone(parent, circular, depth, prototype) {
  ....
} has no method 'getRegExpFlags'

From this:

  child = new RegExp(parent.source, clone.getRegExpFlags(parent));

...

if (global.TESTING) clone.getRegExpFlags = getRegExpFlags;

Put 1.0 on NPM?

There doesn't appear to be a tag so shrinkwrap is failing for me.

problem clone http header

[TypeError: Cannot set property headerSent of # which has only a getter]

I get above error when clone current context HTTP request
Any suggestion please

Bunyan logger cannot be cloned.

I use bunyan in my classes:

let bunyan = require('bunyan');

function MyClass() {
    this.logger = bunyan.createLogger(...);
}
let m = new MyClass()
clone(m, true);
TypeError: Cannot set property remoteAddress of #<Socket> which has only a getter
      at _clone (.../node_modules/clone/clone.js:99:16)

Thanks

Use predicate when cloning

I've just been looking at the code for clone and trying to work out if I can use the 4th param (prototype) to provide a predicate to determine if a property/array element should be cloned. I don't think that it can.

I'm looking to clone an object and to provide that clone function with a predicate that will continue the recursion and copying of properties if the predicate returns true against that object.

For example, let's say I have an object that I want to clone but don't want to clone any properties that have values of null or undefined.

[bug] Doesn't work in strict mode

your module isn't compatible with the strict mode. i get this stack trace:

function _clone(parent, context, child, cIndex) {
    ^^^^^^^^
SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/michael.heuberger/projects/binarykitchen/code/videomail/app/lib/boot/settings.js:2:15)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)

can you make it work for the strict mode? thanks!

TypeError: Method _external called on incompatible receiver #<SecureContext>

It appears that Node.js SecureContext does not like getOwnPropertyDescriptor called on it.

TypeError: Method _external called on incompatible receiver #<SecureContext>
at Function.getOwnPropertyDescriptor (<anonymous>)
at _clone (/var/task/node_modules/clone/clone.js:156:24)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)
at _clone (/var/task/node_modules/clone/clone.js:162:18)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.