Skip to content
Back to Problem Solving and Algorithms course

Work & Development · Web Development & Programming

Free preview

Define a Search Contract Before Coding

Lesson 1 of Problem Solving and Algorithms. Anyone can read this lesson with no account. Every lesson after this one is for students.

Make the problem concrete

Write down what a search accepts, returns and rejects before you write its steps.

Your goal: Write down what a search accepts, returns and rejects before you write its steps.

This course uses JavaScript. Complete Programming Foundations with JavaScript first; if you came from the Python track, that course covers the syntax used here. Run the examples with Node.js 22 or newer (Node 24 is the current LTS release), or paste them into a browser console.

1Make the question precise

An algorithm is a clear sequence of steps for solving a problem. Think of directions for finding a book: you must say whether to look for its number, its title or its topic. "Find a resource" leaves too much undecided. A contract writes down the input, the possible result and the rules for invalid input. Decide how to recognize the same resource and what to return when nothing matches. Then you can check whether the steps follow that contract.

Our first contract receives a previously validated list of resources and a positive safe-integer identifier, a whole-number ID from 1 to Number.MAX_SAFE_INTEGER. Each resource has a distinct identifier. Return the matching record or null; preserve the input order and content. An empty list is permitted. Duplicate identifiers violate the dataset contract and will be checked in a later lesson.

2Worked example

const resources = [
  { id: 1, title: "HTML guide", topic: "Web" },
  { id: 2, title: "CSV practice", topic: "Data" },
];
function findById(records, target) {
  if (!Number.isSafeInteger(target) || target <= 0) {
    throw new TypeError("Target must be a positive safe integer");
  }
  for (const record of records) {
    if (record.id === target) return record;
  }
  return null;
}
console.log(findById(resources, 2).title);
console.log(findById(resources, 9));
console.log(findById([], 1));

Expect CSV practice, then null twice. The loop checks records in their existing order and stops when it finds the identifier. A missing record is a normal search result under this contract; an invalid target type is an error. Distinguishing those conditions prevents an interface from treating a malformed request as a genuine absence.

=== is strict equality: it checks without converting one value's type into another. The string "2" is not automatically the same input as the number 2. An interface can parse a string before calling the function, but that conversion should be explicit and validated. Safe integers stay within the range where JavaScript can represent consecutive whole numbers exactly. Larger numbers can lose that precision, so they are unsuitable for this numeric ID contract.

3Your practice and debugging challenge

  1. Before changing the code, write expected results for the first ID, last ID, missing ID, empty list and invalid target.
  2. Run each example and compare it with your prediction.
  3. Add a third fictional resource. Check which predictions should change and which should stay the same.
  4. Write the steps in ordinary words. For each example, point to the step that returns the answer or rejects the input.

Introduce a bug by returning null inside the loop after the first non-match. Your last-identifier case should now fail even though the first case still succeeds. Move the not-found return after the loop and explain why placement matters. Do not “repair” the failure by sorting the resources: sorting cannot correct an early return.

4Self-check with answer guidance

Question: Which result represents a valid search with no match?

Show answer

Answer: Null.

Question: What should happen for target "2"?

Show answer

Answer: The function throws because the target contract requires a number.

Question: Does a successful first-record example establish that the entire list is searched correctly?

Show answer

Answer: No. Later and missing matches are essential counterexamples.

5Project milestone

Write the identifier-search contract for your resource utility, including dataset validity, input type, not-found behavior and preservation requirements. Keep your five examples as acceptance evidence rather than writing code first and choosing only tests it happens to pass.

Next lesson: Trace a Linear Search One Comparison at a Time.

Continue with the full course

This free preview is lesson 1 only. Enroll to open the rest of Problem Solving and Algorithms.