cid parse (v3)

Revision 3 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

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 lastHypenIndex = id.lastIndexOf('-');
  if (lastHypenIndex === -1) {
    return {
      ownerNodeID: '',
      source: id,
    };
  }

  return {
    ownerNodeID: id.slice(0, lastHypenIndex),
    source: id.slice(lastHypenIndex + 1),
  };
}

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.