Skip to content

Suggestion: Id generation #9

@everythingability

Description

@everythingability

One of the things that this library might do, is help with the generation of an Id field, it seems to me. Something like this perhaps, or maybe you have a better idea of how to implement it.

Or maybe not, I can work with this in my own project.

/**
 * Generates a unique ID for a specific sheet. 
 * Checks against existing 'Id' or 'ID' column to ensure uniqueness.
 * 
 * @param {string} sheetName - The name of the sheet to check for existing IDs.
 * @returns {string} - A unique 8-character ID.
 */
function getUniqueId(sheetName) {
    const gq = new GQuery();
    let newId;
    let exists = true;
    let attempts = 0;
    const maxAttempts = 100; // Safety break

    while (exists && attempts < maxAttempts) {
        attempts++;

        // Generate an 8-character random ID (using first part of UUID)
        newId = Utilities.getUuid().split('-')[0];

        // Check if it exists in the sheet using GQuery
        // Note: We check both common ID spellings found in this project (Id/ID)
        const result = gq.from(sheetName)
            .where(row => {
                const idVal = row.Id !== undefined ? row.Id : row.ID;
                return String(idVal) === newId;
            })
            .get();

        exists = result.rows.length > 0;
    }

    if (attempts >= maxAttempts) {
        throw new Error("Failed to generate a unique ID after " + maxAttempts + " attempts.");
    }

    return newId;
}

/**
 * Example usage of the getUniqueId function
 */
function testUniqueId() {
    const id1 = getUniqueId("Resources");
    Logger.log("New Unique ID for Resources: " + id1);

    const id2 = getUniqueId("Tags");
    Logger.log("New Unique ID for Tags: " + id2);
}

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions