cuid-java icon indicating copy to clipboard operation
cuid-java copied to clipboard

port javascript slug method

Open damianknopp opened this issue 6 years ago • 0 comments

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);
    }

damianknopp avatar Jun 18 '19 21:06 damianknopp