Add string utils with tests

This commit is contained in:
Paul Kaplan 2017-03-20 12:12:38 -04:00
parent 5d2352e471
commit 052ecef91c
2 changed files with 74 additions and 0 deletions

17
src/util/string-util.js Normal file
View file

@ -0,0 +1,17 @@
var StringUtil = function () {};
StringUtil.withoutTrailingDigits = function (s) {
var i = s.length - 1;
while ((i >= 0) && ('0123456789'.indexOf(s.charAt(i)) > -1)) i--;
return s.slice(0, i + 1);
};
StringUtil.unusedName = function (name, existingNames) {
if (existingNames.indexOf(name) < 0) return name;
name = StringUtil.withoutTrailingDigits(name);
var i = 2;
while (existingNames.indexOf(name + i) >= 0) i++;
return name + i;
};
module.exports = StringUtil;

57
test/unit/util_string.js Normal file
View file

@ -0,0 +1,57 @@
var test = require('tap').test;
var StringUtil = require('../../src/util/string-util');
test('withoutTrailingDigits', function (t) {
t.strictEqual(StringUtil.withoutTrailingDigits('boeing747'), 'boeing');
t.strictEqual(StringUtil.withoutTrailingDigits('boeing747 '), 'boeing747 ');
t.strictEqual(StringUtil.withoutTrailingDigits('boeing𝟨'), 'boeing𝟨');
t.strictEqual(StringUtil.withoutTrailingDigits('boeing 747'), 'boeing ');
t.strictEqual(StringUtil.withoutTrailingDigits('747'), '');
t.end();
});
test('unusedName', function (t) {
t.strictEqual(
StringUtil.unusedName(
'name',
['not the same name']
),
'name'
);
t.strictEqual(
StringUtil.unusedName(
'name',
['name']
),
'name2'
);
t.strictEqual(
StringUtil.unusedName(
'name',
['name30']
),
'name'
);
t.strictEqual(
StringUtil.unusedName(
'name',
['name', 'name2']
),
'name3'
);
t.strictEqual(
StringUtil.unusedName(
'name',
['name', 'name3']
),
'name2'
);
t.strictEqual(
StringUtil.unusedName(
'boeing747',
['boeing747']
),
'boeing2' // Yup, this matches scratch-flash...
);
t.end();
});