cid parse (v5)

Revision 5 of this benchmark created on


Setup


  const uuid1 = '550e8400-e29b-41d4-a716-446655440000';
  const uuid2 = '123e4567-e89b-12d3-a456-426614174000';
  const uuid3 = 'f81d4fae-7dec-11d0-a765-00a0c91e6bf6';


const ids = Array(1000).fill('PYa_OJDj@1-BlWSJ_3v@1-cWcVLPol@1' + uuid1);


Test runner

Ready to run.

Testing in
TestOps/sec
plain
const length = 10;
const suffix = '@1';
const pattern = /@\d$/;

function validateID(id) {
  return id.length === length && pattern.test(id);
}

function isUUID(str) {
  return (
    str.length === 36 &&
    str[8] === '-' &&
    str[13] === '-' &&
    str[18] === '-' &&
    str[23] === '-'
  );
}

function parseComputedNodeID(id) {
  const last36str = id.slice(id.length - 36);
  if (isUUID(last36str)) {
    return {
      ownerNodeID: id.slice(0, Math.max(id.length - 36 - 1, 0)),
      source: last36str,
    };
  }

  const last10str = id.slice(id.length - 10);
  if (validateID(last10str)) {
    return {
      ownerNodeID: id.slice(0, Math.max(id.length - 10 - 1, 0)),
      source: last10str,
    };
  }
}

ids.forEach(parseComputedNodeID)
ready
regex
function isUUID(str) {
  return (
    str.length === 36 &&
    str[8] === '-' &&
    str[13] === '-' &&
    str[18] === '-' &&
    str[23] === '-'
  );
}

const pattern = /@\d$/;
function validateID(id) {
  return id.length === length && pattern.test(id);
}

/**
 * ID 문자열에서 마지막 ID와 소유자 노드 ID를 분리합니다.
 * @param id ID 문자열
 * @returns 마지막 ID(source)와 나머지 ID들(ownerNodeID)
 */
function parseComputedNodeID(id) {
  const ids = id.split('-').reverse();

  if (ids.length <= 1) {
    return null;
  }

  let candidate = null;

  for (const [index, item] of ids.entries()) {
    candidate = candidate === null ? item : `${item}-${candidate}`;

    // nanoid인지 확인
    if (validateID(candidate)) {
      return {
        ownerNodeID: ids
          .slice(index + 1)
          .toReversed()
          .join('-'),
        source: candidate,
      };
    }

    // uuid인지 확인
    if (isUUID(candidate)) {
      return {
        ownerNodeID: ids
          .slice(index + 1)
          .toReversed()
          .join('-'),
        source: candidate,
      };
    }
  }

  return null;
}

ids.forEach(parseComputedNodeID)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.