CodeSampleX

샘플

@jest/diff-sequences 30.4.0: diffSequence

검증된 샘플 — npm @jest/diff-sequences 30.4.0: diffSequence. node 22 · linux alpine/x64 · docker에서 contract를 실행해 통과했습니다: diffSequence invokes foundSubsequence…

sha256:f8b1ee685a45971153cbb54dc3f49fc39110a6e24663d8bc3bbf05531dd01b3f

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-27

케이스

HOW
목표
verify pkg:npm/%40jest/diff-sequences@30.4.0
패키지
심벌
  • diffSequence
환경
node 22.23.2
생성일
2026-08-27T22:40:30Z

컨트랙트

  1. diffSequence invokes foundSubsequence callback with length and starting indices for each common chunk between two sequences
  2. diffSequence validates that aLength and bLength are non-negative safe integers and throws TypeError or RangeError otherwise
  3. diffSequence validates that isCommon and foundSubsequence are functions and throws TypeError otherwise
  4. diffSequence handles identical sequences by emitting a single common chunk spanning the entire length
  5. diffSequence handles completely disjoint sequences without invoking foundSubsequence
  6. diffSequence handles empty sequences without error or callback invocations
  7. findCommonSubsequences extracts all matched contiguous intervals between arrays or strings
  8. computeEditScript generates ordered delete, insert, and common operations transforming sequence A into sequence B
  9. longestCommonSubsequence reconstructs the longest shared subsequence of items

파일

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.js

소스 아티팩트 내려받기 (tar.gz)

소스

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:npm/%40jest/diff-sequences@30.4.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/%40jest/diff-sequences@30.4.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:2b1a6dbd0c7ad270935d621c77e5817991954595113037e530aa0e9f017a7159","constraints":{"executionContext":"node"},"contract":["diffSequence invokes foundSubsequence callback with length and starting indices for each common chunk between two sequences","diffSequence validates that aLength and bLength are non-negative safe integers and throws TypeError or RangeError otherwise","diffSequence validates that isCommon and foundSubsequence are functions and throws TypeError otherwise","diffSequence handles identical sequences by emitting a single common chunk spanning the entire length","diffSequence handles completely disjoint sequences without invoking foundSubsequence","diffSequence handles empty sequences without error or callback invocations","findCommonSubsequences extracts all matched contiguous intervals between arrays or strings","computeEditScript generates ordered delete, insert, and common operations transforming sequence A into sequence B","longestCommonSubsequence reconstructs the longest shared subsequence of items"],"goal":"verify pkg:npm/%40jest/diff-sequences@30.4.0","kind":"HOW","packages":["pkg:npm/%40jest/diff-sequences@30.4.0"],"schemaVersion":1,"symbols":["diffSequence"]},"contractCommand":["node","test/contract.js"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/%40jest/diff-sequences@30.4.0"],"schemaVersion":1,"subject":"pkg:npm/%40jest/diff-sequences@30.4.0","symbols":["diffSequence"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const diffSequenceImport = require('@jest/diff-sequences');
const diffSequence = typeof diffSequenceImport === 'function'
  ? diffSequenceImport
  : diffSequenceImport.default;

/**
 * Low-level Myers diff-sequences algorithm.
 * @param {number} aLength - Length of sequence A
 * @param {number} bLength - Length of sequence B
 * @param {(aIndex: number, bIndex: number) => boolean} isCommon - Comparator callback
 * @param {(nCommon: number, aCommon: number, bCommon: number) => void} foundSubsequence - Match callback
 */
function diffSequences(aLength, bLength, isCommon, foundSubsequence) {
  return diffSequence(aLength, bLength, isCommon, foundSubsequence);
}

/**
 * Finds all common subsequences between two indexable sequences (arrays or strings).
 * @param {Array|string} a - First sequence
 * @param {Array|string} b - Second sequence
 * @param {(itemA: any, itemB: any) => boolean} [customCompare] - Optional comparator
 * @returns {Array<{ nCommon: number, aCommon: number, bCommon: number, items: Array|string }>}
 */
function findCommonSubsequences(a, b, customCompare) {
  const isCommon = customCompare
    ? (aIdx, bIdx) => customCompare(a[aIdx], b[bIdx])
    : (aIdx, bIdx) => a[aIdx] === b[bIdx];

  const matches = [];
  diffSequence(a.length, b.length, isCommon, (nCommon, aCommon, bCommon) => {
    const items = typeof a === 'string'
      ? a.slice(aCommon, aCommon + nCommon)
      : a.slice(aCommon, aCommon + nCommon);
    matches.push({
      nCommon,
      aCommon,
      bCommon,
      items
    });
  });
  return matches;
}

/**
 * Computes an edit script of common, delete, and insert operations to transform `a` into `b`.
 * @param {Array|string} a - Source sequence
 * @param {Array|string} b - Target sequence
 * @param {(itemA: any, itemB: any) => boolean} [customCompare] - Optional comparator
 * @returns {Array<{ type: 'common'|'delete'|'insert', aStart: number, aEnd: number, bStart: number, bEnd: number, items: Array|string }>}
 */
function computeEditScript(a, b, customCompare) {
  const commonBlocks = findCommonSubsequences(a, b, customCompare);
  const edits = [];
  let aPos = 0;
  let bPos = 0;

  for (const block of commonBlocks) {
    if (aPos < block.aCommon) {
      edits.push({
        type: 'delete',
        aStart: aPos,
        aEnd: block.aCommon,
        bStart: bPos,
        bEnd: bPos,
        items: a.slice(aPos, block.aCommon)
      });
      aPos = block.aCommon;
    }
    if (bPos < block.bCommon) {
      edits.push({
        type: 'insert',
        aStart: aPos,
        aEnd: aPos,
        bStart: bPos,
        bEnd: block.bCommon,
        items: b.slice(bPos, block.bCommon)
      });
      bPos = block.bCommon;
    }
    edits.push({
      type: 'common',
      aStart: block.aCommon,
      aEnd: block.aCommon + block.nCommon,
      bStart: block.bCommon,
      bEnd: block.bCommon + block.nCommon,
      items: block.items
    });
    aPos = block.aCommon + block.nCommon;
    bPos = block.bCommon + block.nCommon;
  }

  if (aPos < a.length) {
    edits.push({
      type: 'delete',
      aStart: aPos,
      aEnd: a.length,
      bStart: bPos,
      bEnd: bPos,
      items: a.slice(aPos)
    });
  }
  if (bPos < b.length) {
    edits.push({
      type: 'insert',
      aStart: a.length,
      aEnd: a.length,
      bStart: bPos,
      bEnd: b.length,
      items: b.slice(bPos)
    });
  }

  return edits;
}

/**
 * Returns the longest common subsequence of two sequences.
 * @param {Array|string} a - First sequence
 * @param {Array|string} b - Second sequence
 * @param {(itemA: any, itemB: any) => boolean} [customCompare] - Optional comparator
 * @returns {Array|string}
 */
function longestCommonSubsequence(a, b, customCompare) {
  const commonBlocks = findCommonSubsequences(a, b, customCompare);
  if (typeof a === 'string') {
    return commonBlocks.map(block => block.items).join('');
  }
  return commonBlocks.flatMap(block => block.items);
}

module.exports = {
  diffSequence,
  diffSequences,
  findCommonSubsequences,
  computeEditScript,
  longestCommonSubsequence
};
package-lock.json
{
  "name": "sample-jest-diff-sequences",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jest-diff-sequences",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "@jest/diff-sequences": "30.4.0"
      }
    },
    "node_modules/@jest/diff-sequences": {
      "version": "30.4.0",
      "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.4.0.tgz",
      "integrity": "sha512-zOpzlfUs45l6u7jm39qr87JCHUDsaeCtvL+kQe/Vn9jSnRB4/5IPXISm0h9I1vZW/o00Kn4UTJ2MOlhnUGwv3g==",
      "license": "MIT",
      "engines": {
        "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-jest-diff-sequences",
  "version": "1.0.0",
  "private": true,
  "description": "compute diff and longest common subsequence using @jest/diff-sequences",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "@jest/diff-sequences": "30.4.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/%40jest/diff-sequences@30.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40jest/diff-sequences@30.4.0"
  ],
  "symbols": [
    "diffSequence"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.js
'use strict';

const assert = require('assert');
const {
  diffSequence,
  diffSequences,
  findCommonSubsequences,
  computeEditScript,
  longestCommonSubsequence
} = require('../index.js');

function testDiffSequenceBasic() {
  const a = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'];
  const b = ['alpha', 'omega', 'gamma', 'sigma', 'epsilon'];
  const recorded = [];

  diffSequence(
    a.length,
    b.length,
    (aIdx, bIdx) => a[aIdx] === b[bIdx],
    (nCommon, aCommon, bCommon) => {
      recorded.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(recorded.length, 3, 'Should record 3 common subsequences');
  assert.deepStrictEqual(recorded[0], { nCommon: 1, aCommon: 0, bCommon: 0 });
  assert.deepStrictEqual(recorded[1], { nCommon: 1, aCommon: 2, bCommon: 2 });
  assert.deepStrictEqual(recorded[2], { nCommon: 1, aCommon: 4, bCommon: 4 });
}

function testDiffSequenceIdentical() {
  const seq = ['x', 'y', 'z'];
  const recorded = [];

  diffSequences(
    seq.length,
    seq.length,
    (aIdx, bIdx) => seq[aIdx] === seq[bIdx],
    (nCommon, aCommon, bCommon) => {
      recorded.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(recorded.length, 1);
  assert.deepStrictEqual(recorded[0], { nCommon: 3, aCommon: 0, bCommon: 0 });
}

function testDiffSequenceDisjoint() {
  const a = [1, 2, 3];
  const b = [4, 5, 6];
  const recorded = [];

  diffSequence(
    a.length,
    b.length,
    (aIdx, bIdx) => a[aIdx] === b[bIdx],
    (nCommon, aCommon, bCommon) => {
      recorded.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(recorded.length, 0, 'No common subsequences should be found');
}

function testDiffSequenceEmpty() {
  const recorded = [];

  diffSequence(
    0,
    0,
    () => true,
    (nCommon, aCommon, bCommon) => {
      recorded.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(recorded.length, 0);
}

function testDiffSequenceValidation() {
  assert.throws(
    () => diffSequence('3', 3, () => true, () => {}),
    TypeError,
    'aLength must be a number'
  );
  assert.throws(
    () => diffSequence(-1, 3, () => true, () => {}),
    RangeError,
    'aLength must be non-negative'
  );
  assert.throws(
    () => diffSequence(1.5, 3, () => true, () => {}),
    RangeError,
    'aLength must be an integer'
  );
  assert.throws(
    () => diffSequence(3, null, () => true, () => {}),
    TypeError,
    'bLength must be a number'
  );
  assert.throws(
    () => diffSequence(3, 3, null, () => {}),
    TypeError,
    'isCommon must be a function'
  );
  assert.throws(
    () => diffSequence(3, 3, () => true, 'invalid'),
    TypeError,
    'foundSubsequence must be a function'
  );
}

function testFindCommonSubsequences() {
  const s1 = 'ABCDE';
  const s2 = 'ABXDE';
  const matches = findCommonSubsequences(s1, s2);

  assert.strictEqual(matches.length, 2);
  assert.deepStrictEqual(matches[0], {
    nCommon: 2,
    aCommon: 0,
    bCommon: 0,
    items: 'AB'
  });
  assert.deepStrictEqual(matches[1], {
    nCommon: 2,
    aCommon: 3,
    bCommon: 3,
    items: 'DE'
  });
}

function testComputeEditScript() {
  const a = ['apple', 'banana', 'cherry'];
  const b = ['banana', 'date'];
  const edits = computeEditScript(a, b);

  assert.strictEqual(edits.length, 4);
  assert.deepStrictEqual(edits[0], {
    type: 'delete',
    aStart: 0,
    aEnd: 1,
    bStart: 0,
    bEnd: 0,
    items: ['apple']
  });
  assert.deepStrictEqual(edits[1], {
    type: 'common',
    aStart: 1,
    aEnd: 2,
    bStart: 0,
    bEnd: 1,
    items: ['banana']
  });
  assert.deepStrictEqual(edits[2], {
    type: 'delete',
    aStart: 2,
    aEnd: 3,
    bStart: 1,
    bEnd: 1,
    items: ['cherry']
  });
  assert.deepStrictEqual(edits[3], {
    type: 'insert',
    aStart: 3,
    aEnd: 3,
    bStart: 1,
    bEnd: 2,
    items: ['date']
  });
}

function testLongestCommonSubsequence() {
  const strLcs = longestCommonSubsequence('gac', 'agcat');
  assert.strictEqual(strLcs, 'ac');

  const arrLcs = longestCommonSubsequence([1, 2, 3, 4], [2, 4, 6]);
  assert.deepStrictEqual(arrLcs, [2, 4]);
}

function testCustomComparator() {
  const a = ['HELLO', 'WORLD'];
  const b = ['hello', 'everyone'];
  const caseInsensitiveCompare = (x, y) => x.toLowerCase() === y.toLowerCase();

  const matches = findCommonSubsequences(a, b, caseInsensitiveCompare);
  assert.strictEqual(matches.length, 1);
  assert.deepStrictEqual(matches[0], {
    nCommon: 1,
    aCommon: 0,
    bCommon: 0,
    items: ['HELLO']
  });
}

function runAll() {
  testDiffSequenceBasic();
  testDiffSequenceIdentical();
  testDiffSequenceDisjoint();
  testDiffSequenceEmpty();
  testDiffSequenceValidation();
  testFindCommonSubsequences();
  testComputeEditScript();
  testLongestCommonSubsequence();
  testCustomComparator();
  console.log('All diff-sequences contract tests passed successfully.');
}

runAll();

오리진 시더

익명