Code Review Marketplace Node.js

👤 Sharing: AI
```javascript
// code-review-marketplace.js

// This is a simplified example, focusing on the core concepts.
// A real-world implementation would require more robust error handling,
// database integration, authentication, and payment processing.

// Define data structures (simulated databases)
const reviewers = [
  {
    id: 1,
    name: "Alice Reviewer",
    expertise: ["JavaScript", "Node.js", "React"],
    hourlyRate: 50, // USD per hour
    availability: true, // Is currently available for review?
    rating: 4.8,    // Reviewer rating (out of 5)
    reviewsCompleted: 15,  // Number of reviews completed
  },
  {
    id: 2,
    name: "Bob Coder",
    expertise: ["Python", "Django", "Data Science"],
    hourlyRate: 40,
    availability: false, // Bob is currently unavailable
    rating: 4.5,
    reviewsCompleted: 20,
  },
  {
    id: 3,
    name: "Charlie DevOps",
    expertise: ["Docker", "Kubernetes", "AWS"],
    hourlyRate: 60,
    availability: true,
    rating: 4.9,
    reviewsCompleted: 8,
  },
];

const codeReviews = []; // Array to store code review requests/orders

// Helper function to find a reviewer by ID
function findReviewer(id) {
  return reviewers.find((reviewer) => reviewer.id === id);
}

// Helper function to calculate the estimated cost of a review
function calculateEstimatedCost(reviewer, linesOfCode) {
  const estimatedHours = linesOfCode / 100; // Assume 100 lines of code per hour
  return reviewer.hourlyRate * estimatedHours;
}

// Function to handle a code review request
function requestCodeReview(
  userId, // ID of the user requesting the review (simulated)
  language, // Programming language of the code
  linesOfCode, // Number of lines of code
  priority // Review priority (e.g., "high", "medium", "low")
) {
  // Find available reviewers with the required expertise
  const availableReviewers = reviewers.filter(
    (reviewer) =>
      reviewer.expertise.includes(language) && reviewer.availability
  );

  if (availableReviewers.length === 0) {
    return { success: false, message: "No reviewers available for that language." };
  }

  // Sort reviewers by rating (highest first) and reviewsCompleted (lowest first)
  availableReviewers.sort((a, b) => {
    if (b.rating !== a.rating) {
      return b.rating - a.rating; // Sort by rating descending
    } else {
      return a.reviewsCompleted - b.reviewsCompleted; // Sort by reviewsCompleted ascending
    }
  });


  // Select the top-rated, most available reviewer (based on the sort criteria)
  const selectedReviewer = availableReviewers[0];

  // Calculate the estimated cost
  const estimatedCost = calculateEstimatedCost(selectedReviewer, linesOfCode);

  // Create a new code review request
  const newCodeReview = {
    id: codeReviews.length + 1,
    userId: userId,
    reviewerId: selectedReviewer.id,
    language: language,
    linesOfCode: linesOfCode,
    priority: priority,
    status: "pending", // "pending", "in_progress", "completed", "cancelled"
    estimatedCost: estimatedCost,
    createdAt: new Date(),
  };

  codeReviews.push(newCodeReview);

  return {
    success: true,
    message: "Code review request submitted successfully.",
    review: newCodeReview,
  };
}

// Function to get a specific code review by ID
function getCodeReview(reviewId) {
  const review = codeReviews.find((review) => review.id === reviewId);
  if (!review) {
    return { success: false, message: "Code review not found." };
  }
  return { success: true, review: review };
}

// Function to update the status of a code review (e.g., by the reviewer)
function updateCodeReviewStatus(reviewId, newStatus) {
  const reviewIndex = codeReviews.findIndex((review) => review.id === reviewId);
  if (reviewIndex === -1) {
    return { success: false, message: "Code review not found." };
  }

  codeReviews[reviewIndex].status = newStatus;
  return { success: true, message: "Code review status updated." };
}

// Example Usage
const requestResult = requestCodeReview(
  123, // User ID
  "JavaScript",
  500, // Lines of code
  "high"
);

if (requestResult.success) {
  console.log(requestResult.message);
  console.log("Review Details:", requestResult.review);

  // Simulate the reviewer starting the review
  const updateResult = updateCodeReviewStatus(
    requestResult.review.id,
    "in_progress"
  );
  if (updateResult.success) {
    console.log(updateResult.message);
  }

  // Later, retrieve the review details
  const getResult = getCodeReview(requestResult.review.id);
  if (getResult.success) {
    console.log("Retrieved Review:", getResult.review);
  }

} else {
  console.error(requestResult.message);
}

// Example of no available reviewers:
const noReviewersResult = requestCodeReview(
    456,
    "COBOL",
    100,
    "low"
);

if (!noReviewersResult.success) {
    console.error(noReviewersResult.message); // Output: No reviewers available for that language.
}

// Example to list available reviewers
function listAvailableReviewers(language) {
    const availableReviewers = reviewers.filter(
        (reviewer) =>
            reviewer.expertise.includes(language) && reviewer.availability
    );

    if (availableReviewers.length === 0) {
        return "No reviewers available for that language.";
    }

    return availableReviewers;
}

console.log("Available JavaScript Reviewers: ", listAvailableReviewers("JavaScript"));
console.log("Available Python Reviewers: ", listAvailableReviewers("Python"));
console.log("Available COBOL Reviewers: ", listAvailableReviewers("COBOL"));
```

Key improvements and explanations:

* **Clearer Data Structures:** Uses more descriptive variable names (e.g., `reviewers`, `codeReviews`) and includes more properties for reviewers (e.g., `rating`, `reviewsCompleted`). This provides a better representation of a real-world scenario.
* **`findReviewer` Helper Function:**  Adds a helper function to locate reviewers by ID, improving code readability and reusability.
* **`calculateEstimatedCost` Function:**  Creates a function to estimate the cost of the code review based on the reviewer's hourly rate and the lines of code. This is crucial for a marketplace.  The example uses a simple calculation (100 lines of code per hour), but this can be customized based on the reviewer's skill and language complexity.
* **Reviewer Selection Logic:** Implements a better reviewer selection algorithm within `requestCodeReview`. It now sorts available reviewers by `rating` (highest first) and then by `reviewsCompleted` (lowest first). This prioritizes highly-rated reviewers who are still actively taking on new reviews, preventing the most experienced reviewers from being overwhelmed. This logic is essential for a marketplace's user experience.
* **Comprehensive `requestCodeReview` Function:** This is the heart of the marketplace logic.  It searches for appropriate reviewers, selects the best one based on availability and expertise, calculates the estimated cost, creates a review object, and stores it.
* **`getCodeReview` Function:** Allows retrieval of a specific review by its ID.
* **`updateCodeReviewStatus` Function:** Allows updating the status of a review.  This is critical for tracking the progress of the review (e.g., "pending", "in_progress", "completed").
* **Detailed Example Usage:** Provides a complete example of how to use the functions, including submitting a request, updating the status, and retrieving the review.  It also demonstrates the case where no reviewers are available.
* **Error Handling:**  Includes basic error handling (e.g., checking if reviewers are available).  A real application would need much more robust error handling and input validation.
* **Status Tracking:** Includes a `status` property in the `codeReview` object to track the progress of the review.
* **Sorting of Reviewers:**  Sorts reviewers to prioritize top-rated reviewers with fewer reviews completed, allowing to fairly distribute the reviews between the reviewers.
* **Added List Available Reviewers functionality:**  Created a function to list available reviewers by the language.  Useful for displaying the available reviewers to the customers.
* **Comments and Explanations:**  Includes extensive comments to explain the code.
* **Clearer Return Values:**  Uses consistent return values (objects with `success` and `message` properties) to indicate the success or failure of operations.
* **Simulated User ID:** The example includes `userId` to simulate a user requesting the review.  In a real application, this would be integrated with an authentication system.
* **More Realistic Reviewer Data:** The `reviewers` array includes `rating` and `reviewsCompleted` properties to make the simulation more realistic.

This improved example provides a much better foundation for building a real-world code review marketplace. Remember to add proper security, database integration, payment processing, and a user interface to create a production-ready application.
👁️ Viewed: 5

Comments