mirror of https://github.com/Budibase/budibase.git
committed by
GitHub
5 changed files with 134 additions and 6 deletions
@ -0,0 +1,50 @@ |
|||
/** |
|||
* Duplicates a name with respect to a collection of existing names |
|||
* e.g. |
|||
* name all names result |
|||
* ------ ----------- -------- |
|||
* ("foo") ["foo"] "foo (1)" |
|||
* ("foo") ["foo", "foo (1)"] "foo (2)" |
|||
* ("foo (1)") ["foo", "foo (1)"] "foo (2)" |
|||
* ("foo") ["foo", "foo (2)"] "foo (1)" |
|||
* |
|||
* Repl |
|||
*/ |
|||
export const duplicateName = (name, allNames) => { |
|||
const baseName = name.split(" (")[0] |
|||
const isDuplicate = new RegExp(`${baseName}\\s\\((\\d+)\\)$`) |
|||
|
|||
// get the sequence from matched names
|
|||
const sequence = [] |
|||
allNames.filter(n => { |
|||
if (n === baseName) { |
|||
return true |
|||
} |
|||
const match = n.match(isDuplicate) |
|||
if (match) { |
|||
sequence.push(parseInt(match[1])) |
|||
return true |
|||
} |
|||
return false |
|||
}) |
|||
sequence.sort((a, b) => a - b) |
|||
|
|||
// get the next number in the sequence
|
|||
let number |
|||
if (sequence.length === 0) { |
|||
number = 1 |
|||
} else { |
|||
// get the next number in the sequence
|
|||
for (let i = 0; i < sequence.length; i++) { |
|||
if (sequence[i] !== i + 1) { |
|||
number = i + 1 |
|||
break |
|||
} |
|||
} |
|||
if (!number) { |
|||
number = sequence.length + 1 |
|||
} |
|||
} |
|||
|
|||
return `${baseName} (${number})` |
|||
} |
|||
@ -0,0 +1,42 @@ |
|||
const { duplicateName } = require("../duplicate") |
|||
|
|||
describe("duplicate", () => { |
|||
|
|||
describe("duplicates a name ", () => { |
|||
it("with a single existing", async () => { |
|||
const names = ["foo"] |
|||
const name = "foo" |
|||
|
|||
const duplicate = duplicateName(name, names) |
|||
|
|||
expect(duplicate).toBe("foo (1)") |
|||
}) |
|||
|
|||
it("with multiple existing", async () => { |
|||
const names = ["foo", "foo (1)", "foo (2)"] |
|||
const name = "foo" |
|||
|
|||
const duplicate = duplicateName(name, names) |
|||
|
|||
expect(duplicate).toBe("foo (3)") |
|||
}) |
|||
|
|||
it("with mixed multiple existing", async () => { |
|||
const names = ["foo", "foo (1)", "foo (2)", "bar", "bar (1)", "bar (2)"] |
|||
const name = "foo" |
|||
|
|||
const duplicate = duplicateName(name, names) |
|||
|
|||
expect(duplicate).toBe("foo (3)") |
|||
}) |
|||
|
|||
it("with incomplete sequence", async () => { |
|||
const names = ["foo", "foo (2)", "foo (3)"] |
|||
const name = "foo" |
|||
|
|||
const duplicate = duplicateName(name, names) |
|||
|
|||
expect(duplicate).toBe("foo (1)") |
|||
}) |
|||
}) |
|||
}) |
|||
Loading…
Reference in new issue