Add Utilities.Internal.getNextName(name, existingNames)
Function to get the next available name when duplicating something
This commit is contained in:
parent
bf6f1432c5
commit
80f6b857f6
2 changed files with 35 additions and 0 deletions
|
@ -1164,6 +1164,29 @@ Zotero.Utilities.Internal = {
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the next available numbered name that matches a base name, for use when duplicating
|
||||||
|
*
|
||||||
|
* - Given 'Foo' and ['Foo'], returns 'Foo (1)'.
|
||||||
|
* - Given 'Foo (1)' and ['Foo', 'Foo (1)'], returns 'Foo (2)'
|
||||||
|
*/
|
||||||
|
getNextName: function (name, existingNames) {
|
||||||
|
// Trim '(1)', etc.
|
||||||
|
var matches = name.match(/^(.+) \(\d+\)$/);
|
||||||
|
if (matches) {
|
||||||
|
name = matches[1].trim();
|
||||||
|
}
|
||||||
|
var highest = 0;
|
||||||
|
for (let existingName of existingNames) {
|
||||||
|
let matches = existingName.match(/ \((\d+)\)$/);
|
||||||
|
if (matches && matches[1] > highest) {
|
||||||
|
highest = matches[1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return name + ' (' + ++highest + ')';
|
||||||
|
},
|
||||||
|
|
||||||
|
|
||||||
buildLibraryMenu: function (menulist, libraries, selectedLibraryID) {
|
buildLibraryMenu: function (menulist, libraries, selectedLibraryID) {
|
||||||
var menupopup = menulist.firstChild;
|
var menupopup = menulist.firstChild;
|
||||||
while (menupopup.hasChildNodes()) {
|
while (menupopup.hasChildNodes()) {
|
||||||
|
|
|
@ -200,4 +200,16 @@ describe("Zotero.Utilities.Internal", function () {
|
||||||
assert.propertyVal(identifiers[3], "arXiv", "math.GT/0309135");
|
assert.propertyVal(identifiers[3], "arXiv", "math.GT/0309135");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("#getNextName()", function () {
|
||||||
|
it("should get the next available numbered name", function () {
|
||||||
|
var existing = ['Name (1)', 'Name (3)'];
|
||||||
|
assert.equal(Zotero.Utilities.Internal.getNextName('Name', existing), 'Name (4)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should return 'Name (1)' if no numbered names", function () {
|
||||||
|
var existing = ['Name'];
|
||||||
|
assert.equal(Zotero.Utilities.Internal.getNextName('Name', existing), 'Name (1)');
|
||||||
|
});
|
||||||
|
});
|
||||||
})
|
})
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue