Skip to content
This repository was archived by the owner on Jul 28, 2020. It is now read-only.
This repository was archived by the owner on Jul 28, 2020. It is now read-only.

port javascript slug method #5

@damianknopp

Description

@damianknopp

The Javascript implementation has a slug method not in the Java version

You could port the slug method with the following;

    public static String slug() {
        IntBinaryOperator beginIndex = (int a, int b) -> ((a - b) < 0) ? 0 : (a - b);
        String date = Long.toString(new Date().getTime(), BASE);
        String counter = Long.toString(safeCounter(), BASE);
        counter = counter.substring(beginIndex.applyAsInt(counter.length(), 4));
        String fingerPrint = getFingerprint();
        String print = getFingerprint().substring(0, 1) + fingerPrint.substring(beginIndex.applyAsInt(fingerPrint.length(), 1));
        String random = getRandomBlock();
        random = random.substring(beginIndex.applyAsInt(random.length(), 2));
        return date.substring(beginIndex.applyAsInt(date.length(), 2)) + counter + print + random;
    }

    public static boolean isSlug(String slug) {
        int stringLength = slug.length();
        if (stringLength >= 7 && stringLength <= 10) return true;
        return false;
    }

and in the unit test

    @Test
    public void testSlugForCollisions() {
        BooleanSupplier<boolean> hasNoCollisions = () -> {
            int iterations = 4200000;
            Map<String, String> slugs = new HashMap<>();
            for (int i = 0; i < iterations; ++i) {
                String cuid = Cuid.slug();
                if (cuids.containsKey(cuid)) {
                    return false;
                } else {
                    cuids.put(cuid, cuid);
                }
            }

            return true;
        }
        assertEquals(hasNoCollisions(), true);
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions