[Pkg-javascript-commits] [node-clone] 01/02: Imported Upstream version 1.0.2

Julien Puydt julien.puydt at laposte.net
Wed Apr 13 12:44:04 UTC 2016


This is an automated email from the git hooks/post-receive script.

jpuydt-guest pushed a commit to branch master
in repository node-clone.

commit ba775045d0f76bb945966968492a7d1c00adccb0
Author: Julien Puydt <julien.puydt at laposte.net>
Date:   Wed Apr 13 14:08:45 2016 +0200

    Imported Upstream version 1.0.2
---
 .gitignore          |   1 +
 .npmignore          |   1 +
 .travis.yml         |   3 +
 LICENSE             |  18 +++
 README.md           | 126 ++++++++++++++++++
 clone.js            | 160 ++++++++++++++++++++++
 package.json        |  51 +++++++
 test-apart-ctx.html |  22 ++++
 test.html           | 148 +++++++++++++++++++++
 test.js             | 372 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 10 files changed, 902 insertions(+)

diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c2658d7
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+node_modules/
diff --git a/.npmignore b/.npmignore
new file mode 100644
index 0000000..c2658d7
--- /dev/null
+++ b/.npmignore
@@ -0,0 +1 @@
+node_modules/
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..20fd86b
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,3 @@
+language: node_js
+node_js:
+  - 0.10
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..cc3c87b
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,18 @@
+Copyright © 2011-2015 Paul Vorbach <paul at vorba.ch>
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the “Software”), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..0b6ceca
--- /dev/null
+++ b/README.md
@@ -0,0 +1,126 @@
+# clone
+
+[![build status](https://secure.travis-ci.org/pvorb/node-clone.png)](http://travis-ci.org/pvorb/node-clone)
+
+[![info badge](https://nodei.co/npm/clone.png?downloads=true&downloadRank=true&stars=true)](http://npm-stat.com/charts.html?package=clone)
+
+offers foolproof _deep cloning_ of objects, arrays, numbers, strings etc. in JavaScript.
+
+
+## Installation
+
+    npm install clone
+
+(It also works with browserify, ender or standalone.)
+
+
+## Example
+
+~~~ javascript
+var clone = require('clone');
+
+var a, b;
+
+a = { foo: { bar: 'baz' } };  // initial value of a
+
+b = clone(a);                 // clone a -> b
+a.foo.bar = 'foo';            // change a
+
+console.log(a);               // show a
+console.log(b);               // show b
+~~~
+
+This will print:
+
+~~~ javascript
+{ foo: { bar: 'foo' } }
+{ foo: { bar: 'baz' } }
+~~~
+
+**clone** masters cloning simple objects (even with custom prototype), arrays,
+Date objects, and RegExp objects. Everything is cloned recursively, so that you
+can clone dates in arrays in objects, for example.
+
+
+## API
+
+`clone(val, circular, depth)`
+
+  * `val` -- the value that you want to clone, any type allowed
+  * `circular` -- boolean
+
+    Call `clone` with `circular` set to `false` if you are certain that `obj`
+    contains no circular references. This will give better performance if needed.
+    There is no error if `undefined` or `null` is passed as `obj`.
+  * `depth` -- depth to which the object is to be cloned (optional,
+    defaults to infinity)
+
+`clone.clonePrototype(obj)`
+
+  * `obj` -- the object that you want to clone
+
+Does a prototype clone as
+[described by Oran Looney](http://oranlooney.com/functional-javascript/).
+
+
+## Circular References
+
+~~~ javascript
+var a, b;
+
+a = { hello: 'world' };
+
+a.myself = a;
+b = clone(a);
+
+console.log(b);
+~~~
+
+This will print:
+
+~~~ javascript
+{ hello: "world", myself: [Circular] }
+~~~
+
+So, `b.myself` points to `b`, not `a`. Neat!
+
+
+## Test
+
+    npm test
+
+
+## Caveat
+
+Some special objects like a socket or `process.stdout`/`stderr` are known to not
+be cloneable. If you find other objects that cannot be cloned, please [open an
+issue](https://github.com/pvorb/node-clone/issues/new).
+
+
+## Bugs and Issues
+
+If you encounter any bugs or issues, feel free to [open an issue at
+github](https://github.com/pvorb/node-clone/issues) or send me an email to
+<paul at vorba.ch>. I also always like to hear from you, if you’re using my code.
+
+## License
+
+Copyright © 2011-2015 [Paul Vorbach](http://paul.vorba.ch/) and
+[contributors](https://github.com/pvorb/node-clone/graphs/contributors).
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the “Software”), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/clone.js b/clone.js
new file mode 100644
index 0000000..6263759
--- /dev/null
+++ b/clone.js
@@ -0,0 +1,160 @@
+var clone = (function() {
+'use strict';
+
+/**
+ * Clones (copies) an Object using deep copying.
+ *
+ * This function supports circular references by default, but if you are certain
+ * there are no circular references in your object, you can save some CPU time
+ * by calling clone(obj, false).
+ *
+ * Caution: if `circular` is false and `parent` contains circular references,
+ * your program may enter an infinite loop and crash.
+ *
+ * @param `parent` - the object to be cloned
+ * @param `circular` - set to true if the object to be cloned may contain
+ *    circular references. (optional - true by default)
+ * @param `depth` - set to a number if the object is only to be cloned to
+ *    a particular depth. (optional - defaults to Infinity)
+ * @param `prototype` - sets the prototype to be used when cloning an object.
+ *    (optional - defaults to parent prototype).
+*/
+function clone(parent, circular, depth, prototype) {
+  var filter;
+  if (typeof circular === 'object') {
+    depth = circular.depth;
+    prototype = circular.prototype;
+    filter = circular.filter;
+    circular = circular.circular
+  }
+  // maintain two arrays for circular references, where corresponding parents
+  // and children have the same index
+  var allParents = [];
+  var allChildren = [];
+
+  var useBuffer = typeof Buffer != 'undefined';
+
+  if (typeof circular == 'undefined')
+    circular = true;
+
+  if (typeof depth == 'undefined')
+    depth = Infinity;
+
+  // recurse this function so we don't reset allParents and allChildren
+  function _clone(parent, depth) {
+    // cloning null always returns null
+    if (parent === null)
+      return null;
+
+    if (depth == 0)
+      return parent;
+
+    var child;
+    var proto;
+    if (typeof parent != 'object') {
+      return parent;
+    }
+
+    if (clone.__isArray(parent)) {
+      child = [];
+    } else if (clone.__isRegExp(parent)) {
+      child = new RegExp(parent.source, __getRegExpFlags(parent));
+      if (parent.lastIndex) child.lastIndex = parent.lastIndex;
+    } else if (clone.__isDate(parent)) {
+      child = new Date(parent.getTime());
+    } else if (useBuffer && Buffer.isBuffer(parent)) {
+      child = new Buffer(parent.length);
+      parent.copy(child);
+      return child;
+    } else {
+      if (typeof prototype == 'undefined') {
+        proto = Object.getPrototypeOf(parent);
+        child = Object.create(proto);
+      }
+      else {
+        child = Object.create(prototype);
+        proto = prototype;
+      }
+    }
+
+    if (circular) {
+      var index = allParents.indexOf(parent);
+
+      if (index != -1) {
+        return allChildren[index];
+      }
+      allParents.push(parent);
+      allChildren.push(child);
+    }
+
+    for (var i in parent) {
+      var attrs;
+      if (proto) {
+        attrs = Object.getOwnPropertyDescriptor(proto, i);
+      }
+
+      if (attrs && attrs.set == null) {
+        continue;
+      }
+      child[i] = _clone(parent[i], depth - 1);
+    }
+
+    return child;
+  }
+
+  return _clone(parent, depth);
+}
+
+/**
+ * Simple flat clone using prototype, accepts only objects, usefull for property
+ * override on FLAT configuration object (no nested props).
+ *
+ * USE WITH CAUTION! This may not behave as you wish if you do not know how this
+ * works.
+ */
+clone.clonePrototype = function clonePrototype(parent) {
+  if (parent === null)
+    return null;
+
+  var c = function () {};
+  c.prototype = parent;
+  return new c();
+};
+
+// private utility functions
+
+function __objToStr(o) {
+  return Object.prototype.toString.call(o);
+};
+clone.__objToStr = __objToStr;
+
+function __isDate(o) {
+  return typeof o === 'object' && __objToStr(o) === '[object Date]';
+};
+clone.__isDate = __isDate;
+
+function __isArray(o) {
+  return typeof o === 'object' && __objToStr(o) === '[object Array]';
+};
+clone.__isArray = __isArray;
+
+function __isRegExp(o) {
+  return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
+};
+clone.__isRegExp = __isRegExp;
+
+function __getRegExpFlags(re) {
+  var flags = '';
+  if (re.global) flags += 'g';
+  if (re.ignoreCase) flags += 'i';
+  if (re.multiline) flags += 'm';
+  return flags;
+};
+clone.__getRegExpFlags = __getRegExpFlags;
+
+return clone;
+})();
+
+if (typeof module === 'object' && module.exports) {
+  module.exports = clone;
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..b0987ec
--- /dev/null
+++ b/package.json
@@ -0,0 +1,51 @@
+{
+  "name": "clone",
+  "description": "deep cloning of objects and arrays",
+  "tags": [
+    "clone",
+    "object",
+    "array",
+    "function",
+    "date"
+  ],
+  "version": "1.0.2",
+  "repository": {
+    "type": "git",
+    "url": "git://github.com/pvorb/node-clone.git"
+  },
+  "bugs": {
+    "url": "https://github.com/pvorb/node-clone/issues"
+  },
+  "main": "clone.js",
+  "author": "Paul Vorbach <paul at vorba.ch> (http://paul.vorba.ch/)",
+  "contributors": [
+    "Blake Miner <miner.blake at gmail.com> (http://www.blakeminer.com/)",
+    "Tian You <axqd001 at gmail.com> (http://blog.axqd.net/)",
+    "George Stagas <gstagas at gmail.com> (http://stagas.com/)",
+    "Tobiasz Cudnik <tobiasz.cudnik at gmail.com> (https://github.com/TobiaszCudnik)",
+    "Pavel Lang <langpavel at phpskelet.org> (https://github.com/langpavel)",
+    "Dan MacTough (http://yabfog.com/)",
+    "w1nk (https://github.com/w1nk)",
+    "Hugh Kennedy (http://twitter.com/hughskennedy)",
+    "Dustin Diaz (http://dustindiaz.com)",
+    "Ilya Shaisultanov (https://github.com/diversario)",
+    "Nathan MacInnes <nathan at macinn.es> (http://macinn.es/)",
+    "Benjamin E. Coe <ben at npmjs.com> (https://twitter.com/benjamincoe)",
+    "Nathan Zadoks (https://github.com/nathan7)",
+    "Róbert Oroszi <robert+gh at oroszi.net> (https://github.com/oroce)",
+    "Aurélio A. Heckert (http://softwarelivre.org/aurium)",
+    "Guy Ellis (http://www.guyellisrocks.com/)"
+  ],
+  "license": "MIT",
+  "engines": {
+    "node": ">=0.8"
+  },
+  "dependencies": {},
+  "devDependencies": {
+    "nodeunit": "~0.9.0"
+  },
+  "optionalDependencies": {},
+  "scripts": {
+    "test": "nodeunit test.js"
+  }
+}
diff --git a/test-apart-ctx.html b/test-apart-ctx.html
new file mode 100644
index 0000000..4d532bb
--- /dev/null
+++ b/test-apart-ctx.html
@@ -0,0 +1,22 @@
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>Clone Test-Suite (Browser)</title>
+  </head>
+  <body>
+    <script>
+      var data = document.location.search.substr(1).split('&');
+      try {
+        ctx = parent[data[0]];
+        eval(decodeURIComponent(data[1]));
+        window.results = results;
+      } catch(e) {
+        var extra = '';
+        if (e.name == 'SecurityError')
+          extra = 'This test suite needs to be run on an http server.';
+        alert('Apart Context iFrame Error\n' + e + '\n\n' + extra);
+        throw e;
+      }
+    </script>
+  </body>
+</html>
diff --git a/test.html b/test.html
new file mode 100644
index 0000000..a955702
--- /dev/null
+++ b/test.html
@@ -0,0 +1,148 @@
+<!doctype html>
+<html>
+  <head>
+    <meta charset="utf-8">
+    <title>Clone Test-Suite (Browser)</title>
+    <script>
+      var module = {};
+      var tests = exports = module.exports = {};
+
+      function require(moduleName) {
+        if (moduleName == './') {
+          return clone;
+        }
+      }
+
+      function log(str) {
+        logList.innerHTML += '<li>' + str + '</li>';
+      }
+    </script>
+    <script src="clone.js"></script>
+    <script src="test.js"></script>
+  </head>
+  <body>
+    <h1 id="nodeunit-header">Clone Test-Suite (Browser)</h1>
+    Tests started: <span id="testsStarted"></span>;
+    Tests finished: <span id="testsFinished"></span>.
+    <ul id="logList"></ul>
+    <script>
+      /* Methods copied from
+       * https://github.com/caolan/nodeunit/blob/master/lib/assert.js
+       */
+      function isUndefinedOrNull(value) {
+        return value === null || value === undefined;
+      }
+
+      function isArguments(object) {
+        return Object.prototype.toString.call(object) == '[object Arguments]';
+      }
+
+      var _keys = function (obj){
+        if (Object.keys) return Object.keys(obj);
+        if (typeof obj != 'object' && typeof obj != 'function') {
+          throw new TypeError('-');
+        }
+        var keys = [];
+        for(var k in obj) if(obj.hasOwnProperty(k)) keys.push(k);
+        return keys;
+      };
+
+      function objEquiv(a, b) {
+        if (isUndefinedOrNull(a) || isUndefinedOrNull(b))
+          return false;
+
+        if (a.prototype !== b.prototype)
+          return false;
+
+        if (isArguments(a)) {
+          if (!isArguments(b)) return false;
+          a = pSlice.call(a);
+          b = pSlice.call(b);
+          return _deepEqual(a, b);
+        }
+
+        try {
+          var ka = _keys(a), kb = _keys(b), key, i;
+        } catch (e) {
+          return false
+        }
+
+        if (ka.length != kb.length)
+          return false;
+
+        ka.sort();
+        kb.sort();
+
+        for (i = ka.length - 1; i >= 0; i--) {
+          if (ka[i] != kb[i]) return false;
+        }
+
+        for (i = ka.length - 1; i >= 0; i--) {
+          key = ka[i];
+          if (!_deepEqual(a[key], b[key] ))
+            return false;
+        }
+
+        return true;
+      }
+      function _deepEqual(actual, expected) {
+        if (actual === expected) {
+          return true;
+        } else if (actual instanceof Date && expected instanceof Date) {
+          return actual.getTime() === expected.getTime();
+        } else if (actual instanceof RegExp && expected instanceof RegExp) {
+          return actual.source === expected.source &&
+              actual.global === expected.global &&
+              actual.ignoreCase === expected.ignoreCase &&
+              actual.multiline === expected.multiline;
+        } else if (typeof actual != 'object' && typeof expected != 'object') {
+          return actual == expected;
+        } else {
+          return objEquiv(actual, expected);
+        }
+      }
+
+      for (var testName in tests) {
+        setTimeout((function (testName) {
+          try {
+            testsStarted.innerHTML = (parseInt(testsStarted.innerHTML) || 0) + 1;
+            function incFinished() {
+              testsFinished.innerHTML = (parseInt(testsFinished.innerHTML) || 0) + 1;
+            }
+
+            tests[testName]({
+              expect: function (num) {
+                this._expect = num
+              },
+              ok: function (val) {
+                if(!val) throw new Error(val + ' is not ok.')
+              },
+              equal: function (a,b) {
+                if (a != b) throw new Error(a + ' is not equal to ' + b)
+              },
+              notEqual: function (a,b) {
+                if (a == b) throw new Error(a + ' is equal to ' + b)
+              },
+              strictEqual: function (a,b) {
+                if (a !== b) throw new Error(a + ' is not strict equal to ' + b)
+              },
+              deepEqual: function (a,b) {
+                if (!_deepEqual(a,b))
+                  throw new Error(JSON.stringify(a) + ' is not deep equal to ' +
+                                  JSON.stringify(b))
+              },
+              done: function () {
+                log(testName + ' <span style="color:blue">is ok</span>.');
+                incFinished();
+              }
+            });
+          } catch(e) {
+            log(testName + ' <span style="color:red">FAIL.</span> <small>'+ e +'</small>');
+            incFinished();
+            console.log(e);
+          }
+        })(testName), 1);
+      }
+    </script>
+  </body>
+</html>
diff --git a/test.js b/test.js
new file mode 100644
index 0000000..e8b65b3
--- /dev/null
+++ b/test.js
@@ -0,0 +1,372 @@
+var clone = require('./');
+
+function inspect(obj) {
+  seen = [];
+  return JSON.stringify(obj, function (key, val) {
+    if (val != null && typeof val == "object") {
+      if (seen.indexOf(val) >= 0) {
+        return '[cyclic]';
+      }
+
+      seen.push(val);
+    }
+
+    return val;
+  });
+}
+
+// Creates a new VM in node, or an iframe in a browser in order to run the
+// script
+function apartContext(context, script, callback) {
+  var vm = require('vm');
+
+  if (vm) {
+    var ctx = vm.createContext({ ctx: context });
+    callback(vm.runInContext(script, ctx));
+  } else if (document && document.createElement) {
+    var iframe = document.createElement('iframe');
+    iframe.style.display = 'none';
+    document.body.appendChild(iframe);
+
+    var myCtxId = 'tmpCtx' + Math.random();
+
+    window[myCtxId] = context;
+    iframe.src = 'test-apart-ctx.html?' + myCtxId + '&' + encodeURIComponent(script);
+    iframe.onload = function() {
+      try {
+        callback(iframe.contentWindow.results);
+      } catch (e) {
+        throw e;
+      }
+    };
+  } else {
+    console.log('WARNING: cannot create an apart context.');
+  }
+}
+
+exports["clone string"] = function (test) {
+  test.expect(2); // how many tests?
+
+  var a = "foo";
+  test.strictEqual(clone(a), a);
+  a = "";
+  test.strictEqual(clone(a), a);
+
+  test.done();
+};
+
+exports["clone number"] = function (test) {
+  test.expect(5); // how many tests?
+
+  var a = 0;
+  test.strictEqual(clone(a), a);
+  a = 1;
+  test.strictEqual(clone(a), a);
+  a = -1000;
+  test.strictEqual(clone(a), a);
+  a = 3.1415927;
+  test.strictEqual(clone(a), a);
+  a = -3.1415927;
+  test.strictEqual(clone(a), a);
+
+  test.done();
+};
+
+exports["clone date"] = function (test) {
+  test.expect(3); // how many tests?
+
+  var a = new Date;
+  var c = clone(a);
+  test.ok(!!a.getUTCDate && !!a.toUTCString);
+  test.ok(!!c.getUTCDate && !!c.toUTCString);
+  test.equal(a.getTime(), c.getTime());
+
+  test.done();
+};
+
+exports["clone object"] = function (test) {
+  test.expect(1); // how many tests?
+
+  var a = { foo: { bar: "baz" } };
+  var b = clone(a);
+
+  test.deepEqual(b, a);
+
+  test.done();
+};
+
+exports["clone array"] = function (test) {
+  test.expect(2); // how many tests?
+
+  var a = [
+    { foo: "bar" },
+    "baz"
+  ];
+  var b = clone(a);
+
+  test.ok(b instanceof Array);
+  test.deepEqual(b, a);
+
+  test.done();
+};
+
+exports["clone buffer"] = function (test) {
+  if (typeof Buffer == 'undefined') {
+    return test.done();
+  }
+
+  test.expect(1);
+
+  var a = new Buffer("this is a test buffer");
+  var b = clone(a);
+
+  // no underscore equal since it has no concept of Buffers
+  test.deepEqual(b, a);
+  test.done();
+};
+
+exports["clone regexp"] = function (test) {
+  test.expect(5);
+
+  var a = /abc123/gi;
+  var b = clone(a);
+  test.deepEqual(b, a);
+
+  var c = /a/g;
+  test.ok(c.lastIndex === 0);
+
+  c.exec('123a456a');
+  test.ok(c.lastIndex === 4);
+
+  var d = clone(c);
+  test.ok(d.global);
+  test.ok(d.lastIndex === 4);
+
+  test.done();
+};
+
+exports["clone object containing array"] = function (test) {
+  test.expect(1); // how many tests?
+
+  var a = {
+    arr1: [ { a: '1234', b: '2345' } ],
+    arr2: [ { c: '345', d: '456' } ]
+  };
+
+  var b = clone(a);
+
+  test.deepEqual(b, a);
+
+  test.done();
+};
+
+exports["clone object with circular reference"] = function (test) {
+  test.expect(8); // how many tests?
+
+  var c = [1, "foo", {'hello': 'bar'}, function () {}, false, [2]];
+  var b = [c, 2, 3, 4];
+
+  var a = {'b': b, 'c': c};
+  a.loop = a;
+  a.loop2 = a;
+  c.loop = c;
+  c.aloop = a;
+
+  var aCopy = clone(a);
+  test.ok(a != aCopy);
+  test.ok(a.c != aCopy.c);
+  test.ok(aCopy.c == aCopy.b[0]);
+  test.ok(aCopy.c.loop.loop.aloop == aCopy);
+  test.ok(aCopy.c[0] == a.c[0]);
+
+  test.ok(eq(a, aCopy));
+  aCopy.c[0] = 2;
+  test.ok(!eq(a, aCopy));
+  aCopy.c = "2";
+  test.ok(!eq(a, aCopy));
+
+  function eq(x, y) {
+    return inspect(x) === inspect(y);
+  }
+
+  test.done();
+};
+
+exports['clone prototype'] = function (test) {
+  test.expect(3); // how many tests?
+
+  var a = {
+    a: "aaa",
+    x: 123,
+    y: 45.65
+  };
+  var b = clone.clonePrototype(a);
+
+  test.strictEqual(b.a, a.a);
+  test.strictEqual(b.x, a.x);
+  test.strictEqual(b.y, a.y);
+
+  test.done();
+};
+
+exports['clone within an apart context'] = function (test) {
+  var results = apartContext({ clone: clone },
+      "results = ctx.clone({ a: [1, 2, 3], d: new Date(), r: /^foo$/ig })",
+      function (results) {
+    test.ok(results.a.constructor.toString() === Array.toString());
+    test.ok(results.d.constructor.toString() === Date.toString());
+    test.ok(results.r.constructor.toString() === RegExp.toString());
+    test.done();
+  });
+};
+
+exports['clone object with no constructor'] = function (test) {
+  test.expect(3);
+
+  var n = null;
+
+  var a = { foo: 'bar' };
+  a.__proto__ = n;
+  test.ok(typeof a === 'object');
+  test.ok(typeof a !== null);
+
+  var b = clone(a);
+  test.ok(a.foo, b.foo);
+
+  test.done();
+};
+
+exports['clone object with depth argument'] = function (test) {
+  test.expect(6);
+
+  var a = {
+    foo: {
+      bar : {
+        baz : 'qux'
+      }
+    }
+  };
+
+  var b = clone(a, false, 1);
+  test.deepEqual(b, a);
+  test.notEqual(b, a);
+  test.strictEqual(b.foo, a.foo);
+
+  b = clone(a, true, 2);
+  test.deepEqual(b, a);
+  test.notEqual(b.foo, a.foo);
+  test.strictEqual(b.foo.bar, a.foo.bar);
+
+  test.done();
+};
+
+exports['maintain prototype chain in clones'] = function (test) {
+  test.expect(1);
+
+  function T() {}
+
+  var a = new T();
+  var b = clone(a);
+  test.strictEqual(Object.getPrototypeOf(a), Object.getPrototypeOf(b));
+
+  test.done();
+};
+
+exports['parent prototype is overriden with prototype provided'] = function (test) {
+  test.expect(1);
+
+  function T() {}
+
+  var a = new T();
+  var b = clone(a, true, Infinity, null);
+  test.strictEqual(b.__defineSetter__, undefined);
+
+  test.done();
+};
+
+exports['clone object with null children'] = function (test) {
+  test.expect(1);
+  var a = {
+    foo: {
+      bar: null,
+      baz: {
+        qux: false
+      }
+    }
+  };
+
+  var b = clone(a);
+
+  test.deepEqual(b, a);
+  test.done();
+};
+
+exports['clone instance with getter'] = function (test) {
+  test.expect(1);
+  function Ctor() {};
+  Object.defineProperty(Ctor.prototype, 'prop', {
+    configurable: true,
+    enumerable: true,
+    get: function() {
+      return 'value';
+    }
+  });
+
+  var a = new Ctor();
+  var b = clone(a);
+
+  test.strictEqual(b.prop, 'value');
+  test.done();
+};
+
+exports['get RegExp flags'] = function (test) {
+  test.strictEqual(clone.__getRegExpFlags(/a/),   ''  );
+  test.strictEqual(clone.__getRegExpFlags(/a/i),  'i' );
+  test.strictEqual(clone.__getRegExpFlags(/a/g),  'g' );
+  test.strictEqual(clone.__getRegExpFlags(/a/gi), 'gi');
+  test.strictEqual(clone.__getRegExpFlags(/a/m),  'm' );
+
+  test.done();
+};
+
+exports["recognize Array object"] = function (test) {
+  var results = apartContext(null, "results = [1, 2, 3]", function(alien) {
+    var local = [4, 5, 6];
+    test.ok(clone.__isArray(alien)); // recognize in other context.
+    test.ok(clone.__isArray(local)); // recognize in local context.
+    test.ok(!clone.__isDate(alien));
+    test.ok(!clone.__isDate(local));
+    test.ok(!clone.__isRegExp(alien));
+    test.ok(!clone.__isRegExp(local));
+    test.done();
+  });
+};
+
+exports["recognize Date object"] = function (test) {
+  var results = apartContext(null, "results = new Date()", function(alien) {
+    var local = new Date();
+
+    test.ok(clone.__isDate(alien)); // recognize in other context.
+    test.ok(clone.__isDate(local)); // recognize in local context.
+    test.ok(!clone.__isArray(alien));
+    test.ok(!clone.__isArray(local));
+    test.ok(!clone.__isRegExp(alien));
+    test.ok(!clone.__isRegExp(local));
+
+    test.done();
+  });
+};
+
+exports["recognize RegExp object"] = function (test) {
+  var results = apartContext(null, "results = /foo/", function(alien) {
+    var local = /bar/;
+
+    test.ok(clone.__isRegExp(alien)); // recognize in other context.
+    test.ok(clone.__isRegExp(local)); // recognize in local context.
+    test.ok(!clone.__isArray(alien));
+    test.ok(!clone.__isArray(local));
+    test.ok(!clone.__isDate(alien));
+    test.ok(!clone.__isDate(local));
+    test.done();
+  });
+};

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-javascript/node-clone.git



More information about the Pkg-javascript-commits mailing list