CodeSampleX

Пример

@jest/diff-sequences 30.4.0: diffSequences

Проверенный пример — npm @jest/diff-sequences 30.4.0: diffSequences. Контракт выполнен на node 22 · linux debian/x64 · docker и пройден.

sha256:18be5fd27f1d6e50cc54952f131746bce46a3e44b550b7fc51bcb5700f8e0516

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-01

Кейс

HOW
Цель
verify diffSequences in pkg:npm/%40jest/diff-sequences@30.4.0
Пакеты
Символы
  • diffSequences
Окружение
node 22.23.2
Создан
2026-09-01T20:04:12Z

Контракт

  1. diffSequences invokes foundSubsequence callback with length and starting indices for common subsequences between two sequences
  2. diffSequences handles identical sequences by reporting one full-length common subsequence
  3. diffSequences handles completely disjoint sequences without invoking foundSubsequence
  4. diffSequences handles empty sequences without invoking foundSubsequence
  5. diffSequences supports custom comparison logic via the isCommon callback
  6. diffSequences correctly identifies interleaved common subsequences across insertions and deletions
  7. computeDiff produces valid keep, delete, and insert operations to transform sequence A into sequence B
  8. longestCommonSubsequence reconstructs shared elements between strings and arrays

Файлы

  • 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 diffSequences in 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
Demonstrate these symbols/APIs:
  - diffSequences
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:3321d4a6302f17c2c732e6332be3925b129d39c14bb7eeabaa100f69810c2e1a","constraints":{"executionContext":"node"},"contract":["diffSequences invokes foundSubsequence callback with length and starting indices for common subsequences between two sequences","diffSequences handles identical sequences by reporting one full-length common subsequence","diffSequences handles completely disjoint sequences without invoking foundSubsequence","diffSequences handles empty sequences without invoking foundSubsequence","diffSequences supports custom comparison logic via the isCommon callback","diffSequences correctly identifies interleaved common subsequences across insertions and deletions","computeDiff produces valid keep, delete, and insert operations to transform sequence A into sequence B","longestCommonSubsequence reconstructs shared elements between strings and arrays"],"goal":"verify diffSequences in pkg:npm/%40jest/diff-sequences@30.4.0","kind":"HOW","packages":["pkg:npm/%40jest/diff-sequences@30.4.0"],"schemaVersion":1,"symbols":["diffSequences"]},"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":["diffSequences"],"verifierAdapter":"node-typescript@1"}
index.js
'use strict';

const diffSequencesRaw = require('@jest/diff-sequences');
const diffSequences = typeof diffSequencesRaw === 'function'
  ? diffSequencesRaw
  : (diffSequencesRaw && diffSequencesRaw.default) ? diffSequencesRaw.default : diffSequencesRaw;

/**
 * Compare items in two sequences using Myers diff algorithm callback interface.
 * @param {number} aLength - Length of sequence A
 * @param {number} bLength - Length of sequence B
 * @param {(aIndex: number, bIndex: number) => boolean} isCommon - Returns true if item at aIndex equals item at bIndex
 * @param {(nCommon: number, aCommon: number, bCommon: number) => void} foundSubsequence - Called for each common subsequence
 */
function compareSequences(aLength, bLength, isCommon, foundSubsequence) {
  diffSequences(aLength, bLength, isCommon, foundSubsequence);
}

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

  const matches = [];
  diffSequences(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 diff operations ('keep', 'delete', 'insert') transforming sequence a into sequence b.
 * @param {Array|string} a - Source sequence
 * @param {Array|string} b - Target sequence
 * @param {(itemA: any, itemB: any) => boolean} [customCompare] - Optional comparator
 * @returns {Array<{ op: 'keep'|'delete'|'insert', items: Array|string, aStart: number, aEnd: number, bStart: number, bEnd: number }>}
 */
function computeDiff(a, b, customCompare) {
  const matches = findCommonSequences(a, b, customCompare);
  const edits = [];
  let aPos = 0;
  let bPos = 0;

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

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

  return edits;
}

/**
 * Computes 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 matches = findCommonSequences(a, b, customCompare);
  if (typeof a === 'string') {
    return matches.map(m => m.items).join('');
  }
  return matches.flatMap(m => m.items);
}

module.exports = {
  diffSequences,
  compareSequences,
  findCommonSequences,
  computeDiff,
  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": "verify diffSequences in @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 diffSequences in pkg:npm/%40jest/diff-sequences@30.4.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/%40jest/diff-sequences@30.4.0"
  ],
  "symbols": [
    "diffSequences"
  ],
  "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 {
  diffSequences,
  compareSequences,
  findCommonSequences,
  computeDiff,
  longestCommonSubsequence
} = require('../index.js');

function testDiffSequencesCallbackInvocation() {
  const a = ['x', 'a', 'b', 'y', 'c'];
  const b = ['m', 'a', 'b', 'n', 'c'];
  const chunks = [];

  diffSequences(
    a.length,
    b.length,
    (aIndex, bIndex) => a[aIndex] === b[bIndex],
    (nCommon, aCommon, bCommon) => {
      chunks.push({ nCommon, aCommon, bCommon });
    }
  );

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

function testDiffSequencesIdentical() {
  const seq = ['alpha', 'beta', 'gamma'];
  const chunks = [];

  diffSequences(
    seq.length,
    seq.length,
    (aIndex, bIndex) => seq[aIndex] === seq[bIndex],
    (nCommon, aCommon, bCommon) => {
      chunks.push({ nCommon, aCommon, bCommon });
    }
  );

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

function testDiffSequencesDisjoint() {
  const a = ['a', 'b', 'c'];
  const b = ['x', 'y', 'z'];
  const chunks = [];

  diffSequences(
    a.length,
    b.length,
    (aIndex, bIndex) => a[aIndex] === b[bIndex],
    (nCommon, aCommon, bCommon) => {
      chunks.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(chunks.length, 0, 'Disjoint sequences should produce no common chunks');
}

function testDiffSequencesEmpty() {
  const chunks = [];

  diffSequences(
    0,
    0,
    () => true,
    (nCommon, aCommon, bCommon) => {
      chunks.push({ nCommon, aCommon, bCommon });
    }
  );

  assert.strictEqual(chunks.length, 0, 'Empty sequences should produce no common chunks');
}

function testDiffSequencesCustomComparator() {
  const a = ['HELLO', 'WORLD'];
  const b = ['hello', 'developer'];
  const chunks = [];

  compareSequences(
    a.length,
    b.length,
    (aIndex, bIndex) => a[aIndex].toLowerCase() === b[bIndex].toLowerCase(),
    (nCommon, aCommon, bCommon) => {
      chunks.push({ nCommon, aCommon, bCommon });
    }
  );

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

function testInterleavedSequences() {
  const a = 'kitten';
  const b = 'sitting';
  const matches = findCommonSequences(a, b);

  // 'k' != 's', 'itt' == 'itt', 'e' != 'i', 'n' == 'n', '' != 'g'
  assert.strictEqual(matches.length, 2);
  assert.deepStrictEqual(matches[0], { nCommon: 3, aCommon: 1, bCommon: 1, items: 'itt' });
  assert.deepStrictEqual(matches[1], { nCommon: 1, aCommon: 5, bCommon: 5, items: 'n' });
}

function testComputeDiffOperations() {
  const a = ['line1', 'line2', 'line3'];
  const b = ['line1', 'line2-modified', 'line3', 'line4'];
  const edits = computeDiff(a, b);

  assert.strictEqual(edits.length, 5);
  // line1 (keep)
  assert.strictEqual(edits[0].op, 'keep');
  assert.deepStrictEqual(edits[0].items, ['line1']);
  // line2 (delete)
  assert.strictEqual(edits[1].op, 'delete');
  assert.deepStrictEqual(edits[1].items, ['line2']);
  // line2-modified (insert)
  assert.strictEqual(edits[2].op, 'insert');
  assert.deepStrictEqual(edits[2].items, ['line2-modified']);
  // line3 (keep)
  assert.strictEqual(edits[3].op, 'keep');
  assert.deepStrictEqual(edits[3].items, ['line3']);
  // line4 (insert)
  assert.strictEqual(edits[4].op, 'insert');
  assert.deepStrictEqual(edits[4].items, ['line4']);
}

function testLongestCommonSubsequence() {
  const strLcs = longestCommonSubsequence('ABCEFG', 'BDFG');
  assert.strictEqual(strLcs, 'BFG');

  const arrLcs = longestCommonSubsequence([10, 20, 30, 40], [20, 40, 60]);
  assert.deepStrictEqual(arrLcs, [20, 40]);
}

function runContract() {
  testDiffSequencesCallbackInvocation();
  testDiffSequencesIdentical();
  testDiffSequencesDisjoint();
  testDiffSequencesEmpty();
  testDiffSequencesCustomComparator();
  testInterleavedSequences();
  testComputeDiffOperations();
  testLongestCommonSubsequence();
  console.log('Contract tests passed successfully.');
}

runContract();

Исходный сидер

аноним