CodeSampleX

Exemple

p-locate 5.0.0: pLocate

Échantillon vérifié pour npm p-locate 5.0.0: pLocate. Le contrat s'est exécuté sur node 22 · linux alpine/x64 · docker et a réussi.

sha256:32943f55f4980b0857355c33635c069265b7eeeb42d6d4748b96aceec2d69e96

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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

Cas

HOW
Objectif
verify pLocate in pkg:npm/p-locate@5.0.0
Paquets
Symboles
  • pLocate
Environnement
node 22.23.2
Créé
2026-08-27T10:04:11Z

Contrat

  1. pLocate resolves with the first element in iterable that satisfies an async or sync tester function
  2. pLocate resolves to undefined when no element in iterable satisfies tester
  3. pLocate supports iterables containing promises that resolve to elements
  4. pLocate preserves input order by default when async testers resolve out of order
  5. pLocate with preserveOrder false returns the fastest resolving match
  6. pLocate respects concurrency option to limit parallel tester executions
  7. pLocate works with non-array iterables such as Set and generator functions
  8. pLocate propagates errors when a tester throws or an input promise rejects

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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 pLocate in pkg:npm/p-locate@5.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/p-locate@5.0.0
Demonstrate these symbols/APIs:
  - pLocate

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:1105c50067421428e93227c4971784aebbcced3dc0094d848933868f8ec5564a","contract":["pLocate resolves with the first element in iterable that satisfies an async or sync tester function","pLocate resolves to undefined when no element in iterable satisfies tester","pLocate supports iterables containing promises that resolve to elements","pLocate preserves input order by default when async testers resolve out of order","pLocate with preserveOrder false returns the fastest resolving match","pLocate respects concurrency option to limit parallel tester executions","pLocate works with non-array iterables such as Set and generator functions","pLocate propagates errors when a tester throws or an input promise rejects"],"goal":"verify pLocate in pkg:npm/p-locate@5.0.0","kind":"HOW","packages":["pkg:npm/p-locate@5.0.0"],"schemaVersion":1,"symbols":["pLocate"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/p-locate@5.0.0"],"schemaVersion":1,"subject":"pkg:npm/p-locate@5.0.0","symbols":["pLocate"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-p-locate",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-p-locate",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "p-locate": "5.0.0"
      }
    },
    "node_modules/p-limit": {
      "version": "3.1.0",
      "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
      "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==",
      "license": "MIT",
      "dependencies": {
        "yocto-queue": "^0.1.0"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/p-locate": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz",
      "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==",
      "license": "MIT",
      "dependencies": {
        "p-limit": "^3.0.2"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/yocto-queue": {
      "version": "0.1.0",
      "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
      "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==",
      "license": "MIT",
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    }
  }
}
package.json
{
  "name": "sample-p-locate",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "p-locate": "5.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pLocate in pkg:npm/p-locate@5.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/p-locate@5.0.0"
  ],
  "symbols": [
    "pLocate"
  ]
}
src/index.mjs
import pLocate from 'p-locate';

/**
 * Finds the first element in an iterable that satisfies the tester function.
 * @param {Iterable} iterable Input iterable of values or promises.
 * @param {Function} tester Predicate function returning boolean or Promise<boolean>.
 * @param {object} [options] Optional settings (concurrency, preserveOrder).
 * @returns {Promise<*|undefined>} The first matching element, or undefined.
 */
export async function findFirstMatch(iterable, tester, options) {
  return pLocate(iterable, tester, options);
}

/**
 * Finds the first matching element without preserving input order (fastest resolving match).
 * @param {Iterable} iterable Input iterable of values or promises.
 * @param {Function} tester Predicate function returning boolean or Promise<boolean>.
 * @param {number} [concurrency=Infinity] Concurrency limit.
 * @returns {Promise<*|undefined>} The first resolved matching element, or undefined.
 */
export async function findFirstResolvedMatch(iterable, tester, concurrency = Infinity) {
  return pLocate(iterable, tester, { preserveOrder: false, concurrency });
}

/**
 * Finds the first matching element with limited concurrency.
 * @param {Iterable} iterable Input iterable of values or promises.
 * @param {Function} tester Predicate function returning boolean or Promise<boolean>.
 * @param {number} concurrency Concurrency limit.
 * @returns {Promise<*|undefined>} The first matching element, or undefined.
 */
export async function findWithConcurrency(iterable, tester, concurrency) {
  return pLocate(iterable, tester, { concurrency });
}

export { pLocate };
export default pLocate;
test/contract.mjs
import assert from 'node:assert/strict';
import pLocate from 'p-locate';
import { findFirstMatch, findFirstResolvedMatch, findWithConcurrency } from '../src/index.mjs';

// 1. pLocate resolves with the first element in iterable that satisfies an async or sync tester function
{
  const items = ['apple', 'banana', 'cherry'];
  const syncResult = await pLocate(items, (item) => item.startsWith('b'));
  assert.equal(syncResult, 'banana');

  const asyncResult = await pLocate(items, async (item) => {
    await new Promise((resolve) => setTimeout(resolve, 10));
    return item.length > 5;
  });
  assert.equal(asyncResult, 'banana');

  const helperResult = await findFirstMatch(items, (item) => item === 'cherry');
  assert.equal(helperResult, 'cherry');
}

// 2. pLocate resolves to undefined when no element in iterable satisfies tester
{
  const numbers = [1, 2, 3, 4, 5];
  const result = await pLocate(numbers, (num) => num > 100);
  assert.equal(result, undefined);

  const emptyResult = await pLocate([], () => true);
  assert.equal(emptyResult, undefined);
}

// 3. pLocate supports iterables containing promises that resolve to elements
{
  const promiseItems = [
    Promise.resolve('alpha'),
    new Promise((resolve) => setTimeout(() => resolve('beta'), 15)),
    Promise.resolve('gamma'),
  ];
  const result = await pLocate(promiseItems, async (item) => item.startsWith('b'));
  assert.equal(result, 'beta');
}

// 4. pLocate preserves input order by default when async testers resolve out of order
{
  const items = ['first', 'second', 'third'];
  const delayMap = {
    first: 40,
    second: 20,
    third: 5,
  };

  const result = await pLocate(items, async (item) => {
    await new Promise((resolve) => setTimeout(resolve, delayMap[item]));
    return true; // all match, but 'first' should win due to order preservation
  });

  assert.equal(result, 'first');
}

// 5. pLocate with preserveOrder false returns the fastest resolving match
{
  const items = ['slow-match', 'fast-match', 'medium-match'];
  const delayMap = {
    'slow-match': 50,
    'fast-match': 10,
    'medium-match': 30,
  };

  const result = await pLocate(
    items,
    async (item) => {
      await new Promise((resolve) => setTimeout(resolve, delayMap[item]));
      return true;
    },
    { preserveOrder: false }
  );

  assert.equal(result, 'fast-match');

  const helperResult = await findFirstResolvedMatch(
    items,
    async (item) => {
      await new Promise((resolve) => setTimeout(resolve, delayMap[item]));
      return true;
    }
  );
  assert.equal(helperResult, 'fast-match');
}

// 6. pLocate respects concurrency option to limit parallel tester executions
{
  const items = [1, 2, 3, 4, 5, 6];
  let active = 0;
  let maxActive = 0;

  const result = await pLocate(
    items,
    async (item) => {
      active++;
      maxActive = Math.max(maxActive, active);
      await new Promise((resolve) => setTimeout(resolve, 20));
      active--;
      return item === 4;
    },
    { concurrency: 2 }
  );

  assert.equal(result, 4);
  assert.equal(maxActive, 2);

  let helperMaxActive = 0;
  let helperActive = 0;
  const helperRes = await findWithConcurrency(
    items,
    async (item) => {
      helperActive++;
      helperMaxActive = Math.max(helperMaxActive, helperActive);
      await new Promise((resolve) => setTimeout(resolve, 15));
      helperActive--;
      return item === 3;
    },
    1
  );
  assert.equal(helperRes, 3);
  assert.equal(helperMaxActive, 1);
}

// 7. pLocate works with non-array iterables such as Set and generator functions
{
  const set = new Set(['cat', 'dog', 'elephant']);
  const setResult = await pLocate(set, (animal) => animal.length > 5);
  assert.equal(setResult, 'elephant');

  function* generateValues() {
    yield 10;
    yield 20;
    yield 30;
  }
  const genResult = await pLocate(generateValues(), (val) => val >= 20);
  assert.equal(genResult, 20);
}

// 8. pLocate propagates errors when a tester throws or an input promise rejects
{
  const errorTester = pLocate([1, 2, 3], () => {
    throw new Error('tester failed');
  });
  await assert.rejects(errorTester, {
    name: 'Error',
    message: 'tester failed',
  });

  const rejectedInput = pLocate(
    [Promise.reject(new Error('input rejected'))],
    () => true
  );
  await assert.rejects(rejectedInput, {
    name: 'Error',
    message: 'input rejected',
  });
}

console.log('Contract tests passed successfully.');

Seeder d'origine

anonyme