Skip to content

Instantly share code, notes, and snippets.

@develohpanda
Last active April 17, 2020 03:10
Show Gist options
  • Save develohpanda/717750abf140a9631a6aa4df2d3a7ce0 to your computer and use it in GitHub Desktop.
Save develohpanda/717750abf140a9631a6aa4df2d3a7ce0 to your computer and use it in GitHub Desktop.
I wanted a challenge
const node = (item?: string, separator?: string) => `${item && `${separator}${item}`}`;
const nodes = [
node(parentEntityType),
node(currentEntityType, ':'),
node(fieldName, '::'),
node(fieldName && entityId, ':::'),
];
return new Key(nodes.join(''));
@Kyle-Muir
Copy link

Kyle-Muir commented Apr 17, 2020

if no parentEntityType and no entity id -> currentEntityType
if no parentEntityType and an entity id -> currentEntityType + entityId
if no fieldName and no entity id        -> parentEntityType + currentEntityType
if no fieldname and an entity id        -> parentEntityType + currentEntityType + ::entityId
if no entityId                          -> parentEntityType + currentEntityType + ::fieldName
if entityId                             -> parentEntityType + currentEntityType + ::fieldName + :::entityId

OG Code:

const EntityTypeKeyGenerator = ({
    parentEntityType,
    currentEntityType,
    fieldName,
    entityId
}: EntityTypeKeyFields): Key => {
    if (!parentEntityType) {
        if (!entityId) {
            return new Key(currentEntityType);
        }
        return new Key(`${currentEntityType}:${entityId}`);
    }
    if (!fieldName) {
        if (!entityId) {
            return new Key(`${parentEntityType}:${currentEntityType}`);
        }
        return new Key(`${parentEntityType}:${currentEntityType}::${entityId}`);
    }
    if (!entityId) {
        return new Key(`${parentEntityType}:${currentEntityType}::${fieldName}`);
    }
    return new Key(`${parentEntityType}:${currentEntityType}::${fieldName}:::${entityId}`);
};

My version:

Changed rule to say that ::: for fieldNames with entityIds dies and all entityIds are now prefixed with :: instead.

const EntityTypeKeyGenerator = ({
    parentEntityType,
    currentEntityType,
    fieldName,
    entityId
}: EntityTypeKeyFields): Key => {
    const entityType = [parentEntityType, currentEntityType].filter(Boolean).join(':');
    const entityWithField = [entityType, fieldName].filter(Boolean).join('::');
    const entityWithFieldAndId = [entityWithField, entityId].filter(Boolean).join('::');
    return new Key(entityWithFieldAndId);
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment