From db7e066e20f3ce8c3ab99f67bf3edc96afa81eee Mon Sep 17 00:00:00 2001 From: Caleb Wright Date: Thu, 7 Aug 2014 15:36:01 -0400 Subject: [PATCH] Add optional argument isDeep to File.clone - Allows passing in isDeep:false to perform a shallow clone. --- README.md | 6 ++++-- index.js | 9 ++++++--- test/File.js | 22 +++++++++++++++++++++- 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 99db34e..90129ad 100644 --- a/README.md +++ b/README.md @@ -77,9 +77,11 @@ Returns true if file.contents is a Stream. Returns true if file.contents is null. -### clone() +### clone([opt]) -Returns a new File object with all attributes cloned. Custom attributes are deep-cloned. +Returns a new File object with all attributes cloned. Custom attributes are deep-cloned by default. + +If opt.isDeep is false, a shallow clone will be performed. ### pipe(stream[, opt]) diff --git a/index.js b/index.js index bd96adc..57219a3 100644 --- a/index.js +++ b/index.js @@ -2,7 +2,7 @@ var path = require('path'); var cloneStats = require('clone-stats'); var _ = require('lodash'); -var cloneDeep = _.cloneDeep; +var cloneShallow = _.clone; var isBuffer = require('./lib/isBuffer'); var isStream = require('./lib/isStream'); @@ -44,12 +44,15 @@ File.prototype.isDirectory = function() { return this.isNull() && this.stat && this.stat.isDirectory(); }; -File.prototype.clone = function() { +File.prototype.clone = function(opt) { + if (!opt) opt = {}; + if (typeof opt.isDeep === 'undefined') opt.isDeep = true; + var clone = new File(); Object.keys(this).forEach(function(key) { if (key !== '_contents' && key !== 'stat') { - clone[key] = cloneDeep(this[key]); + clone[key] = cloneShallow(this[key], opt.isDeep); } }, this); diff --git a/test/File.js b/test/File.js index c6ee31a..26ab21c 100644 --- a/test/File.js +++ b/test/File.js @@ -251,7 +251,7 @@ describe('File', function() { done(); }); - + it('should copy custom properties', function(done) { var options = { cwd: "/", @@ -270,7 +270,27 @@ describe('File', function() { file2.base.should.equal(file.base); file2.path.should.equal(file.path); file2.custom.should.not.equal(file.custom); + + done(); + }); + + it('should support shallow cloning of custom properties', function(done) { + var options = { + cwd: "/", + base: "/test/", + path: "/test/test.coffee", + contents: null + }; + + var file = new File(options); + file.custom = { a: { b: 'custom property' } }; + + var file2 = file.clone({ isDeep: false }); + + file2.should.not.equal(file, 'refs should be different'); + file2.custom.should.not.equal(file.custom); file2.custom.a.should.equal(file.custom.a); + file2.custom.a.b.should.equal(file.custom.a.b); done(); });