Skip to content

Commit 2d22e44

Browse files
committed
fix(stringifier): do not truncate if string length is short enough
1 parent a8e4e65 commit 2d22e44

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

strategies.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,14 @@ function truncate (size) {
109109
return function (acc, x) {
110110
var orig = acc.push, ret;
111111
acc.push = function (str) {
112-
var truncated = str.substring(0, size);
113-
orig.call(acc, truncated + acc.options.snip);
112+
var savings = str.length - size,
113+
truncated;
114+
if (savings <= size) {
115+
orig.call(acc, str);
116+
} else {
117+
truncated = str.substring(0, size);
118+
orig.call(acc, truncated + acc.options.snip);
119+
}
114120
};
115121
ret = next(acc, x);
116122
acc.push = orig;

test/customization_test.js

+15-2
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ describe('strategies', function () {
3232
beforeEach(function () {
3333
this.student = new Student('tom', 10, 'M');
3434
this.anonymous = new AnonStudent('mary', 9, 'F');
35+
this.longNameStudent = new Student('the_long_name_man', 18, 'M');
3536
});
3637

3738
it('always', function () {
@@ -182,7 +183,19 @@ describe('strategies', function () {
182183
return true;
183184
})
184185
};
185-
assert.equal(stringify(this.student, null, handlers), 'Student{name:"to..(snip),age:10,gender:"M"}');
186+
assert.equal(stringify(this.longNameStudent, null, handlers), 'Student{name:"th..(snip),age:18,gender:"M"}');
187+
});
188+
189+
it('do not truncate if string length is short enough', function () {
190+
var handlers = {
191+
'Student': s.object(function (kvp) {
192+
if (kvp.key === 'name') {
193+
return 3;
194+
}
195+
return true;
196+
})
197+
};
198+
assert.equal(stringify(this.student, null, handlers), 'Student{name:"tom",age:10,gender:"M"}');
186199
});
187200

188201
it('per-property truncate bare handler', function () {
@@ -194,7 +207,7 @@ describe('strategies', function () {
194207
return true;
195208
})
196209
};
197-
assert.equal(stringify(this.student, null, handlers), 'Student{name:"to..(snip),age:10,gender:"M"}');
210+
assert.equal(stringify(this.longNameStudent, null, handlers), 'Student{name:"th..(snip),age:18,gender:"M"}');
198211
});
199212

200213

0 commit comments

Comments
 (0)