cid parse

Benchmark created on


Setup

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

Test runner

Ready to run.

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

function parseComputedNodeID(id) {
  // {id}-{*} format
  if (id[10] === '-') {
    const front = id.substring(0, 10);
    if (validateID(front)) {
      return { ownerNodeID: front, source: id.substring(11) };
    }
  }

  // {nanoid}-{*} format
  if (id[21] === '-') {
    return { ownerNodeID: id.substring(0, 21), source: id.substring(22) };
  }

  // {uuid}-{*} format
  if (id[36] === '-') {
    return { ownerNodeID: id.substring(0, 36), source: id.substring(37) };
  }

  return null;
}

ids.forEach(parseComputedNodeID)
ready
regex
function parseComputedNodeID(id) {
  // UUID 패턴 (8-4-4-4-12 형식)
  const uuidPattern =
    /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

  // 문자열의 길이가 0이면 빈 결과 반환
  if (!id || id.length === 0) {
    return null;
  }

  // 하이픈으로 구분된 모든 세그먼트
  const segments = id.split('-');

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

  // UUID가 될 수 있는 마지막 세그먼트 조합 찾기
  for (let i = 0; i < segments.length; i++) {
    // 마지막부터 i+1개 세그먼트 가져오기
    const lastSegments = segments.slice(segments.length - i - 1);
    const potentialId = lastSegments.join('-');

    // UUID 패턴인지 확인
    if (uuidPattern.test(potentialId)) {
      return {
        source: potentialId,
        ownerNodeID: segments.slice(0, segments.length - i - 1).join('-'),
      };
    }
  }

  // UUID를 찾지 못했다면 마지막 세그먼트가 nanoid임
  return {
    source: segments[segments.length - 1],
    ownerNodeID: segments.slice(0, segments.length - 1).join('-'),
  };
}

ids.forEach(parseComputedNodeID)
ready

Revisions

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