Skip to content

Commit

Permalink
add $.copy for 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
clux committed Sep 30, 2014
1 parent 71b6746 commit fb3f4be
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
@@ -1,3 +1,9 @@
1.0.0 / 2014-09-30
==================
* Add `$.copy` to shallow copy an element
* `$.constant(n)` now uses `$.copy`
* `$.replicate(o)` now uses `$.copy` (thus will additionally copy objects)

0.5.2 / 2014-09-02
==================
* Move coverage to tests area to avoid confusing browserify
Expand Down
14 changes: 12 additions & 2 deletions autonomy.js
Expand Up @@ -27,9 +27,19 @@ $.id = function (x) {
$.noop = function () {
};

$.copy = function (val) {
if (Array.isArray(val)) {
return val.slice();
}
if (val === Object(val)) {
return $.extend({}, val);
}
return val;
};

$.constant = function (val) {
return function () {
return val;
return $.copy(val);
};
};

Expand Down Expand Up @@ -171,7 +181,7 @@ $.range = function (start, stop, step) {
$.replicate = function (times, el) {
var res = [];
for (var i = 0; i < times; i += 1) {
res.push(Array.isArray(el) ? el.slice() : el);
res.push($.copy(el));
}
return res;
};
Expand Down
26 changes: 26 additions & 0 deletions test/basic.js
Expand Up @@ -133,3 +133,29 @@ exports.get = function (t) {
t.deepEqual(objs.map($.get('ZZ', 'AA')).filter(op.neq()), [], "harvest shallow undefs");
t.done();
};

exports.constant = function (t) {
var o = {bah: 'woot'};
var fno = $.constant(o);
var ocpy = fno();
t.deepEqual(o, ocpy, 'constant copies properties');
ocpy.hi = 'there';
t.equal(o.hi, undefined, 'constant returns new copy of object');

var a = [1];
var fna = $.constant(a);
var acpy = fna();
t.deepEqual(acpy, a, 'constant copies array contents shallowly');
acpy.push(2);
t.equal(a.length, 1, 'constant slices arrays so leaves original unmodified');

// other types do not need copying as they are not returned by reference:
var s = "hi";
var fns = $.constant(s);
var scpy = fns();
t.equal(s, scpy, 'constant copies string');
scpy = 'bi';
t.equals(s, 'hi', 'we did not overwrite original');

t.done();
};

0 comments on commit fb3f4be

Please sign in to comment.