ronantakizawa/codereview-bench huggingface dataset:
Repository: date-fns/date-fns
File: src/isWithinInterval/index.ts (TypeScript)

Code before:
 *
 * @example
 * // For the date within the interval:
 * isWithinInterval(new Date(2014, 0, 3), {
 *   start: new Date(2014, 0, 1),
 *   end: new Date(2014, 0, 7)
 * })
 * //=> true
 *
 * @example
 * // For the date outside of the interval:
 * isWithinInterval(new Date(2014, 0, 10), {
 *   start: new Date(2014, 0, 1),
 *   end: new Date(2014, 0, 7)
 * })
 * //=> false
 *
 * @example
 * // For date equal to interval start:
 * isWithinInterval(date, { start, end: date }) // => true
 *
 * @example
 * // For date equal to interval end:
 * isWithinInterval(date, { start: date, end }) // => true
 */
export default function isWithinInterval(dirtyDate: Date | number, interval: Interval) {
  requiredArgs(2, arguments)

  const time = toDate(dirtyDate).getTime()
  const startTime = toDate(interval.start).getTime()
  const endTime = toDate(interval.end).getTime()

  // Throw an exception if start date is after end date or if any date is `Invalid Date`
  if (!(startTime <= endTime)) {
    throw new RangeError('Invalid interval')
  }

  return time >= startTime && time <= endTime
}


Review comment (suggestion):
```suggestion
export default function isWithinInterval(dirtyDate: Date | number, interval: Interval): boolean {
```

Code after:
 *
 * @example
 * // For the date within the interval:
 * isWithinInterval(new Date(2014, 0, 3), {
 *   start: new Date(2014, 0, 1),
 *   end: new Date(2014, 0, 7)
 * })
 * //=> true
 *
 * @example
 * // For the date outside of the interval:
 * isWithinInterval(new Date(2014, 0, 10), {
 *   start: new Date(2014, 0, 1),
 *   end: new Date(2014, 0, 7)
 * })
 * //=> false
 *
 * @example
 * // For date equal to interval start:
 * isWithinInterval(date, { start, end: date }) // => true
 *
 * @example
 * // For date equal to interval end:
 * isWithinInterval(date, { start: date, end }) // => true
 */
export default function isWithinInterval(dirtyDate: Date | number, interval: Interval): boolean {
  requiredArgs(2, arguments)

  const time = toDate(dirtyDate).getTime()
  const startTime = toDate(interval.start).getTime()
  const endTime = toDate(interval.end).getTime()

  // Throw an exception if start date is after end date or if any date is `Invalid Date`
  if (!(startTime <= endTime)) {
    throw new RangeError('Invalid interval')
  }

  return time >= startTime && time <= endTime
}
Repository: date-fns/date-fns
File: src/sub/index.ts (TypeScript)

Code before:
 *   weeks: 1,
 *   days: 7,
 *   hours: 5,
 *   minutes: 9,
 *   seconds: 30
 * })
 * //=> Mon Sep 1 2014 10:19:50
 */
export default function sub(
  dirtyDate: Date | number,
  duration: Duration
): Date {
  requiredArgs(2, arguments)

  if (!duration || typeof duration !== 'object') return new Date(NaN)

  const years = duration.years ? toInteger(duration.years) : 0
  const months = duration.months ? toInteger(duration.months) : 0
  const weeks = duration.weeks ? toInteger(duration.weeks) : 0
  const days = duration.days ? toInteger(duration.days) : 0
  const hours = duration.hours ? toInteger(duration.hours) : 0
  const minutes = duration.minutes ? toInteger(duration.minutes) : 0
  const seconds = duration.seconds ? toInteger(duration.seconds) : 0

  // Subtract years and months
  const dateWithoutMonths = subMonths(dirtyDate, months + years * 12)

  // Subtract weeks and days
  const dateWithoutDays = subDays(dateWithoutMonths, days + weeks * 7)

  // Subtract hours, minutes and seconds
  const minutestoSub = minutes + hours * 60
  const secondstoSub = seconds + minutestoSub * 60
  const mstoSub = secondstoSub * 1000
  const finalDate = new Date(dateWithoutDays.getTime() - mstoSub)

  return finalDate
}


Review comment (suggestion):
```suggestion
  const dateWithoutMonths = subMonths(date, months + years * 12)
```

Code after:
 *   weeks: 1,
 *   days: 7,
 *   hours: 5,
 *   minutes: 9,
 *   seconds: 30
 * })
 * //=> Mon Sep 1 2014 10:19:50
 */
export default function sub(
  date: Date | number,
  duration: Duration
): Date {
  requiredArgs(2, arguments)

  if (!duration || typeof duration !== 'object') return new Date(NaN)

  const years = duration.years ? toInteger(duration.years) : 0
  const months = duration.months ? toInteger(duration.months) : 0
  const weeks = duration.weeks ? toInteger(duration.weeks) : 0
  const days = duration.days ? toInteger(duration.days) : 0
  const hours = duration.hours ? toInteger(duration.hours) : 0
  const minutes = duration.minutes ? toInteger(duration.minutes) : 0
  const seconds = duration.seconds ? toInteger(duration.seconds) : 0

  // Subtract years and months
  const dateWithoutMonths = subMonths(date, months + years * 12)

  // Subtract weeks and days
  const dateWithoutDays = subDays(dateWithoutMonths, days + weeks * 7)

  // Subtract hours, minutes and seconds
  const minutestoSub = minutes + hours * 60
  const secondstoSub = seconds + minutestoSub * 60
  const mstoSub = secondstoSub * 1000
  const finalDate = new Date(dateWithoutDays.getTime() - mstoSub)

  return finalDate
}
Repository: date-fns/date-fns
File: src/getWeekOfMonth/index.ts (TypeScript)

Code before:
import getDate from '../getDate/index'
import getDay from '../getDay/index'
import startOfMonth from '../startOfMonth/index'
import { LocaleOptions, WeekStartOptions } from '../types'
import requiredArgs from '../_lib/requiredArgs/index'
import toInteger from '../_lib/toInteger/index'

/**
 * @name getWeekOfMonth
 * @category Week Helpers
 * @summary Get the week of the month of the given date.
 *
 * @description
 * Get the week of the month of the given date.
 *
 * ### v2.0.0 breaking changes:
 *
 * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
 *
 * @param {Date|Number} date - the given date
 * @param {Object} [options] - an object with options.
 * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
 * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
 * @returns {Number} the week of month
 * @throws {TypeError} 1 argument required
 * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 inclusively
 *
 * @example
 * // Which week of the month is 9 November 2017?

Review comment (suggestion):
```suggestion
import type { LocaleOptions, WeekStartOptions } from '../types'
```

Code after:
import getDate from '../getDate/index'
import getDay from '../getDay/index'
import startOfMonth from '../startOfMonth/index'
import type { LocaleOptions, WeekStartOptions } from '../types'
import requiredArgs from '../_lib/requiredArgs/index'
import toInteger from '../_lib/toInteger/index'

/**
 * @name getWeekOfMonth
 * @category Week Helpers
 * @summary Get the week of the month of the given date.
 *
 * @description
 * Get the week of the month of the given date.
 *
 * ### v2.0.0 breaking changes:
 *
 * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
 *
 * @param {Date|Number} date - the given date
 * @param {Object} [options] - an object with options.
 * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
 * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
 * @returns {Number} the week of month
 * @throws {TypeError} 1 argument required
 * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6 inclusively
 *
 * @example
 * // Which week of the month is 9 November 2017?
Repository: date-fns/date-fns
File: src/roundToNearestHours/index.ts (TypeScript)

Code before:
import { getRoundingMethod } from "../_lib/getRoundingMethod/index.js";
import { constructFrom } from "../constructFrom/index.js";
import { toDate } from "../toDate/index.js";
import type { NearestHoursOptions, RoundingOptions } from "../types";

/**
 * The {@link roundToNearestHours} function options.
 */
export interface RoundToNearestHoursOptions
  extends NearestHoursOptions,
    RoundingOptions {}

/**
 * @name roundToNearestHours
 * @category Hour Helpers
 * @summary Rounds the given date to the nearest hour
 *
 * @description
 * Rounds the given date to the nearest hour (or number of hours).
 * Rounds up when the given date is exactly between the nearest round hours.
 *
 * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
 *
 * @param date - The date to round
 * @param options - An object with options.
 *
 * @returns The new date rounded to the closest hour
 *
 * @example

Review comment (suggestion):
```suggestion
import type { NearestHoursOptions, RoundingOptions } from "../types.js";
```

Code after:
import { getRoundingMethod } from "../_lib/getRoundingMethod/index.js";
import { constructFrom } from "../constructFrom/index.js";
import { toDate } from "../toDate/index.js";
import type {
  NearestHours,
  NearestToUnitOptions,
  RoundingOptions,
} from "../types.js";

/**
 * The {@link roundToNearestHours} function options.
 */
export interface RoundToNearestHoursOptions
  extends NearestToUnitOptions<NearestHours>,
    RoundingOptions {}

/**
 * @name roundToNearestHours
 * @category Hour Helpers
 * @summary Rounds the given date to the nearest hour
 *
 * @description
 * Rounds the given date to the nearest hour (or number of hours).
 * Rounds up when the given date is exactly between the nearest round hours.
 *
 * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
 *
 * @param date - The date to round
 * @param options - An object with options.
Repository: date-fns/date-fns
File: src/locale/it-CH/index.ts (TypeScript)

Code before:
import type { Locale } from '../types'
import formatDistance from '../it/_lib/formatDistance/index'
import formatRelative from '../it/_lib/formatRelative/index'
import localize from '../it/_lib/localize/index'
import match from '../it/_lib/match/index'
import formatLong from './_lib/formatLong/index'

/**
 * @type {Locale}
 * @category Locales
 * @summary Italian locale (Switzerland).
 * @language Italian
 * @author Mike Peyer [@maic66]{@link https://github.com/maic66}
 */
const locale: Locale = {
  code: 'it-CH',
  formatDistance: formatDistance,
  formatLong: formatLong,
  formatRelative: formatRelative,
  localize: localize,
  match: match,
  options: {
    weekStartsOn: 1 /* Monday */,
    firstWeekContainsDate: 4,
  },
}

export default locale


Review comment (suggestion):
The `@iso-639-2 ita` jsdoc annotation is missing. It's OK that it's not unique, it identifies the language and not the locale.

Code after:
import type { Locale } from '../types'
import formatDistance from '../it/_lib/formatDistance/index'
import formatRelative from '../it/_lib/formatRelative/index'
import localize from '../it/_lib/localize/index'
import match from '../it/_lib/match/index'
import formatLong from './_lib/formatLong/index'

/**
 * @type {Locale}
 * @category Locales
 * @summary Italian locale (Switzerland).
 * @language Italian
 * @iso-639-2 ita
 * @author Mike Peyer [@maic66]{@link https://github.com/maic66}
 */
const locale: Locale = {
  code: 'it-CH',
  formatDistance: formatDistance,
  formatLong: formatLong,
  formatRelative: formatRelative,
  localize: localize,
  match: match,
  options: {
    weekStartsOn: 1 /* Monday */,
    firstWeekContainsDate: 4,
  },
}

export default locale
Repository: date-fns/date-fns
File: src/locale/ru/_lib/formatRelative/index.ts (TypeScript)

Code before:
import isSameUTCWeek from '../../../../_lib/isSameUTCWeek/index'
import { FormatRelativeFn, FormatRelativeTokenFn } from '../../../types'
import { toDate } from '../../../../index'

const accusativeWeekdays = [
  'воскресенье',
  'понедельник',
  'вторник',
  'среду',
  'четверг',
  'пятницу',
  'субботу',
]

function lastWeek(day: Day): string {
  const weekday = accusativeWeekdays[day]

  switch (day) {
    case 0:
      return "'в прошлое " + weekday + " в' p"
    case 1:
    case 2:
    case 4:
      return "'в прошлый " + weekday + " в' p"
    case 3:
    case 5:
    case 6:
      return "'в прошлую " + weekday + " в' p"

Review comment (suggestion):
```suggestion
import { toDate } from '../../../../index'
import type { Day } from '../../../../types'
import isSameUTCWeek from '../../../../_lib/isSameUTCWeek/index'
import type { FormatRelativeFn, FormatRelativeTokenFn } from '../../../types'
```

Code after:
import type { Day } from '../../../../types'
import isSameUTCWeek from '../../../../_lib/isSameUTCWeek/index'
import type { FormatRelativeFn, FormatRelativeFnOptions } from '../../../types'

const accusativeWeekdays = [
  'воскресенье',
  'понедельник',
  'вторник',
  'среду',
  'четверг',
  'пятницу',
  'субботу',
]

function lastWeek(day: Day): string {
  const weekday = accusativeWeekdays[day]

  switch (day) {
    case 0:
      return "'в прошлое " + weekday + " в' p"
    case 1:
    case 2:
    case 4:
      return "'в прошлый " + weekday + " в' p"
    case 3:
    case 5:
    case 6:
      return "'в прошлую " + weekday + " в' p"
Repository: date-fns/date-fns
File: src/locale/ru/_lib/localize/index.ts (TypeScript)

Code before:
import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index'
import { LocalizeFn } from '../../../types'
import type { Quarter } from '../../../../types'

const eraValues = {
  narrow: ['до н.э.', 'н.э.'] as const,
  abbreviated: ['до н. э.', 'н. э.'] as const,
  wide: ['до нашей эры', 'нашей эры'] as const,
}

const quarterValues = {
  narrow: ['1', '2', '3', '4'] as const,
  abbreviated: ['1-й кв.', '2-й кв.', '3-й кв.', '4-й кв.'] as const,
  wide: ['1-й квартал', '2-й квартал', '3-й квартал', '4-й квартал'] as const,
}

const monthValues = {
  narrow: ['Я', 'Ф', 'М', 'А', 'М', 'И', 'И', 'А', 'С', 'О', 'Н', 'Д'] as const,
  abbreviated: [
    'янв.',
    'фев.',
    'март',
    'апр.',
    'май',
    'июнь',
    'июль',

Review comment (suggestion):
```suggestion
import type { Quarter } from '../../../../types'
import type { LocalizeFn } from '../../../types'
import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index'
```

Code after:
import type { Quarter } from '../../../../types'
import type { Localize, LocalizeFn } from '../../../types'
import buildLocalizeFn from '../../../_lib/buildLocalizeFn/index'

const eraValues = {
  narrow: ['до н.э.', 'н.э.'] as const,
  abbreviated: ['до н. э.', 'н. э.'] as const,
  wide: ['до нашей эры', 'нашей эры'] as const,
}

const quarterValues = {
  narrow: ['1', '2', '3', '4'] as const,
  abbreviated: ['1-й кв.', '2-й кв.', '3-й кв.', '4-й кв.'] as const,
  wide: ['1-й квартал', '2-й квартал', '3-й квартал', '4-й квартал'] as const,
}

const monthValues = {
  narrow: ['Я', 'Ф', 'М', 'А', 'М', 'И', 'И', 'А', 'С', 'О', 'Н', 'Д'] as const,
  abbreviated: [
    'янв.',
    'фев.',
    'март',
    'апр.',
    'май',
    'июнь',
    'июль',
Repository: date-fns/date-fns
File: src/types.ts (TypeScript)

Code before:

export interface AdditionalTokensOptions {
  useAdditionalWeekYearTokens?: boolean
  useAdditionalDayOfYearTokens?: boolean
}

export interface FormatDistanceOptions {
  includeSeconds?: boolean
  addSuffix?: boolean
}

export interface FormatDistanceStrictOptions {
  addSuffix?: boolean
  unit?: Unit
  roundingMethod?: 'floor' | 'ceil' | 'round'
}

export interface FormatDurationOptions {
  format?: (keyof Duration)[]
  zero?: boolean
  delimiter?: string
}

export interface RoundToNearestMinutesOptions {
  nearestTo?: number
  mode?: 'floor' | 'ceil'
}

export interface AreIntervalsOverlappingOptions {
  inclusive?: boolean
}

export type IntlOptionsUnit =
  | 'year'
  | 'quarter'
  | 'month'
  | 'week'
  | 'day'
  | 'hour'
  | 'minute'
  | 'second'


Review comment (suggestion):
Instead of adding `mode` here please reuse the code from here:
https://github.com/date-fns/date-fns/blob/master/src/_lib/roundingMethods/index.ts

Code after:

export interface AdditionalTokensOptions {
  useAdditionalWeekYearTokens?: boolean
  useAdditionalDayOfYearTokens?: boolean
}

export interface FormatDistanceOptions {
  includeSeconds?: boolean
  addSuffix?: boolean
}

export interface FormatDistanceStrictOptions {
  addSuffix?: boolean
  unit?: Unit
  roundingMethod?: 'floor' | 'ceil' | 'round'
}

export interface FormatDurationOptions {
  format?: (keyof Duration)[]
  zero?: boolean
  delimiter?: string
}

export interface AreIntervalsOverlappingOptions {
  inclusive?: boolean
}

export type IntlOptionsUnit =
  | 'year'
  | 'quarter'
  | 'month'
  | 'week'
  | 'day'
  | 'hour'
  | 'minute'
  | 'second'
Repository: date-fns/date-fns
File: src/constructFrom/test.ts (TypeScript)

Code before:

    assert.ok(result instanceof Date)
    assert.deepStrictEqual(result, value)
  })

  it('should create a new custom Date instance using the constructor from the reference date', () => {
    class CustomDate extends Date {}
    const referenceDate = new CustomDate('2023-10-25T12:00:00')
    const value = new CustomDate('2023-10-26T12:00:00')

    const result = constructFrom(referenceDate, value)

    assert.ok(result instanceof CustomDate)
    assert.deepStrictEqual(result, value)
    assert.strictEqual(result.constructor, referenceDate.constructor)
  })

  it('should create a new custom Date instance using a number as the reference date', () => {
    class CustomDate extends Date {}
    const referenceDate = new CustomDate(1635158400000) // October 25, 2023
    const value = new CustomDate('2023-10-26T12:00:00')

    const result = constructFrom(referenceDate, value)

    assert.ok(result instanceof CustomDate)
    assert.deepStrictEqual(result, value)
    assert.strictEqual(result.constructor, CustomDate)
  })
})


Review comment (suggestion):
This case is equal to the previous one, it doesn't matter for the function how you create `CustomDate`.

For the symmetry, you better add test case where both `referenceDate` and `value` are numbers.

Code after:

    assert.ok(result instanceof Date);
    assert.deepStrictEqual(result, value);
  });

  it("should create a new custom Date instance using the constructor from the reference date", () => {
    class CustomDate extends Date {}
    const referenceDate = new CustomDate("2023-10-25T12:00:00");
    const value = new CustomDate("2023-10-26T12:00:00");

    const result = constructFrom(referenceDate, value);

    assert.ok(result instanceof CustomDate);
    assert.deepStrictEqual(result, value);
    assert.strictEqual(result.constructor, referenceDate.constructor);
  });

  it("should create a new Date instance using numbers as both referenceDate and value", () => {
    const referenceDate = 1635158400000; // October 25, 2023
    const value = 1635244800000; // October 26, 2023

    const result = constructFrom(referenceDate, value);

    assert.ok(result instanceof Date);
    assert.deepStrictEqual(result.getTime(), value);
  });
});
Repository: denoland/deno
File: cli/args/flags.rs (Rust)

Code before:
  deno run --allow-read=/etc jsr:@std/http/file-server

Specifying the filename '-' to read the file from stdin.

  curl https://examples.deno.land/hello-world.ts | deno run -",
    )
}

fn serve_subcommand() -> Command {
  runtime_args(Command::new("serve"), true, true)
    .arg(
      Arg::new("port")
        .long("port")
        .help("The TCP port to serve on, defaulting to 8000.")
        .value_parser(value_parser!(NonZeroU16)),
    )
    .arg(check_arg(false))
    .arg(watch_arg(true))
    .arg(watch_exclude_arg())
    .arg(hmr_arg(true))
    .arg(no_clear_screen_arg())
    .arg(executable_ext_arg())
    .arg(
      script_arg()
        .required_unless_present("v8-flags")
        .trailing_var_arg(true),
    )
    .arg(env_file_arg())
    .arg(no_code_cache_arg())
    .about("Run a server")
    .long_about("")
}

fn task_subcommand() -> Command {
  Command::new("task")
    .about("Run a task defined in the configuration file")
    .long_about(
      "Run a task defined in the configuration file

  deno task build",
    )
    .defer(|cmd| {
      cmd
        .allow_external_subcommands(true)
        .subcommand_value_name("TASK")
        .arg(config_arg())
        .arg(
          Arg::new("cwd")
            .long("cwd")
            .value_name("DIR")
            .help("Specify the directory to run the task in")

Review comment (suggestion):
Add `host` flag for completeness sake 🙏  I think it's also worth noting that these flags would override setting defined in `export default {}` configuration

Code after:
Grant permission to read allow-listed files from disk:

  deno run --allow-read=/etc jsr:@std/http/file-server

Specifying the filename '-' to read the file from stdin.

  curl https://examples.deno.land/hello-world.ts | deno run -",
    )
}

fn serve_host_validator(host: &str) -> Result<String, String> {
  if Url::parse(&format!("internal://{host}:9999")).is_ok() {
    Ok(host.to_owned())
  } else {
    Err(format!("Bad serve host: {host}"))
  }
}

fn serve_subcommand() -> Command {
  runtime_args(Command::new("serve"), true, true)
    .arg(
      Arg::new("port")
        .long("port")
        .help("The TCP port to serve on, defaulting to 8000.")
        .value_parser(value_parser!(NonZeroU16)),
    )
    .arg(
      Arg::new("host")
        .long("host")
        .help("The TCP address to serve on, defaulting to 0.0.0.0 (all interfaces).")
        .value_parser(serve_host_validator),
    )
    .arg(check_arg(false))
    .arg(watch_arg(true))
    .arg(watch_exclude_arg())
    .arg(hmr_arg(true))
    .arg(no_clear_screen_arg())
    .arg(executable_ext_arg())
    .arg(
      script_arg()
        .required_unless_present("v8-flags")
        .trailing_var_arg(true),
    )
    .arg(env_file_arg())
    .arg(no_code_cache_arg())
    .about("Run a server")
    .long_about("Run a server defined in a main module

The serve command uses the default exports of the main module to determine which
servers to start.