All files / src/irr/transform transform.ts

100% Statements 21/21
100% Branches 3/3
100% Functions 6/6
100% Lines 19/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51    2x 2x     22x 22x   22x       45x 18x     27x   27x 1x       26x   26x               23x     2x 7x 1x     6x 23x         5x    
import { XirrInput, InternalXirrInput } from '../definition'
 
const DATE_PATTERNS = [/^(\d{4})[-/]?(\d{2})[-/]?(\d{2})$/]
const DAYS_TO_MS = 24 * 60 * 60 * 1000
 
function calculateDaysBetweenStrict(from: Date, to: Date): number {
  const fromDays = Math.floor(from.valueOf() / DAYS_TO_MS)
  const toDays = Math.floor(to.valueOf() / DAYS_TO_MS)
 
  return toDays - fromDays
}
 
function parseDate(date: string | Date): Date {
  if (date instanceof Date) {
    return date
  }
 
  const pattern = DATE_PATTERNS.find(pattern => pattern.test(date))
 
  if (!pattern) {
    throw new Error(`Invalid date pattern: ${date}`)
  }
 
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  const [, year, month, day] = date.match(pattern)!
 
  return new Date(
    parseInt(year, 10),
    parseInt(month, 10) - 1,
    parseInt(day, 10),
  )
}
 
function calculateDaysBetween(from: string | Date, to: string | Date): number {
  return calculateDaysBetweenStrict(parseDate(from), parseDate(to))
}
 
export function transform(inputs: XirrInput[]): InternalXirrInput[] {
  if (inputs.length === 0) {
    return []
  }
 
  const { date } = inputs[0]
  const transformedInputs = inputs.map(input => ({
    amount: input.amount,
    day: calculateDaysBetween(date, input.date),
  }))
 
  return transformedInputs
}