Certainly! Let's break down the sampleBuildings function step by step.
Function Overview
The function sampleBuildings takes a pool of buildings and returns a sample of 3 buildings from this pool. The sample is constructed such that each building in the sample has a unique shape. The shapes of the buildings are assumed to be stored in a Map called BUILDING_SHAPES, where the keys are the buildings and the values are their respective shapes.
Detailed Explanation
-
Initialization:
const results = [];
const remaining = [...pool];
const seenShapes = new Set();
results: An empty array that will store the final sample of buildings.
remaining: A copy of the input pool array. This is used to keep track of the buildings that are still available to be sampled.
seenShapes: A Set to keep track of the shapes that have already been included in the results.
-
Sampling Loop:
while (results.length < 3) {
The loop continues until results contains 3 buildings.
-
Random Selection:
const index = Math.floor(Math.random() * remaining.length);
const candidate = remaining[index];
index: A randomly generated index within the range of the remaining array.
candidate: The building at the randomly selected index.
-
Remove Candidate from Remaining:
remaining[index] = remaining[remaining.length - 1];
remaining.pop();
This code swaps the randomly selected building with the last element in the remaining array and then removes the last element. This ensures that the remaining array does not have holes and maintains a consistent length for random selection.
-
Check Shape:
const shape = BUILDING_SHAPES.get(candidate);
if (!seenShapes.has(shape)) {
results.push(candidate);
seenShapes.add(shape);
}
shape: The shape of the candidate building, retrieved from the BUILDING_SHAPES map.
- The
if statement checks if the shape has already been seen (i.e., is in the seenShapes set).
- If the shape is unique (not in
seenShapes), the candidate is added to the results array, and the shape is added to the seenShapes set.
Return Value
return results;
The function returns the results array, which contains 3 buildings with unique shapes.
Summary
The sampleBuildings function randomly selects 3 buildings from the provided pool such that each selected building has a unique shape. It uses a Set to track seen shapes and ensures that the sampling process is efficient by removing selected buildings from the remaining array.