DEV Community

Discussion on: Daily Challenge #216 - Rainfall

Collapse
 
differentmatt profile image
Matt Lott

JS solution

const parseData = (string) => {
  // Return map of cities and their rainfalls, assumes well-formed data
  return string.split('\n').map(line => line.split(':'))
    .map(cityMonths => {
      return {
        city: cityMonths[0],
        rainfalls: cityMonths[1].split(',')
          .map(month => parseFloat(month.split(' ')[1]))
          .filter(r => !isNaN(r))
      }
    })
    .reduce((m, cityRainfalls) => {
      m[cityRainfalls.city] = cityRainfalls.rainfalls
      return m
    }, {})
}

const calcMean = (nums) => nums.reduce((t, n) => t + n, 0) / nums.length

const calcVariance = (nums) => {
  const mean = calcMean(nums)
  return calcMean(nums.map(num => Math.pow(num - mean, 2)))
}

const mean = (town, string) => {
  const cityRainfallsMap = parseData(string)
  if (!cityRainfallsMap[town] || cityRainfallsMap[town].length < 1) return -1
  return calcMean(cityRainfallsMap[town])
}

const variance = (town, string) => {
  const cityRainfallsMap = parseData(string)
  if (!cityRainfallsMap[town] || cityRainfallsMap[town].length < 1) return -1
  return calcVariance(cityRainfallsMap[town])
}


// Tests assume data, data1 in scope

const test = (fn, town, string, expected) => {
  const result = fn(town, string)
  console.log(`${town} ${result} === ${expected} ?`)
}

test(variance, "London", data, 57.42833333333374)
test(mean, "London", data, 51.199999999999996)

test(mean, "Seattle", data, -1)
test(variance, "Seattle", data, -1)

test(mean, "Seattle", "Seattle:", -1)
test(variance, "Seattle", "Seattle:", -1)

test(variance, 'Beijing', data1, '4437.0380555556')
test(variance, 'Lima', data, '1.5790972222222')