DEV Community

loading...

Discussion on: Daily Challenge #216 - Rainfall

Collapse
empereol profile image
Empereol

TypeScript

/**
 * Math Utilities
 */
interface Math {
  mean(...values: number[]): number;
  variance(...values: number[]): number;
}

Math.mean = (...values: number[]): number => values.reduce((t, v) => (t += v), 0) / values.length;

Math.variance = (...values: number[]): number => {
  const mean = Math.mean(...values);
  return Math.mean(...values.map(v => (v - mean) ** 2));
};

/**
 * Rainfall
 */
interface RainData {
  town: string;
  values: number[];
}

function createRainData(data: string): RainData[] {
  return data.split(/\n/).map(line => ({
    town: line.split(':')[0].trim(),
    values: line.match(/\d+\.\d+/gi).map(Number)
  }));
}

function getRainfall(town: string, data: string): number[] {
  const rainData = createRainData(data).find(d => d.town === town);
  return rainData ? rainData.values : [-1];
}

function mean(town: string, data: string): number {
  return Math.mean(...getRainfall(town, data));
}

function variance(town: string, data: string): number {
  return Math.variance(...getRainfall(town, data));
}