<commit_before>"use strict"

const ancestry = JSON.parse(require("./ancestry"))
const log = console.log;

function average(array) {
  let plus = (a,b) => a + b;
  return array.reduce(plus) / array.length
}

function zipWith(f, xs, ys) {
  if(xs.length === 0) return []
  if(ys.length === 0) return []
  let x = xs[0],
      y = ys[0]
  xs = xs.slice(1)
  ys = ys.slice(1)
  return [f(x, y)].concat(zipWith(f, xs, ys))
}

/* HISTORICAL LIFE EXPECTANCY */
// log( ancestry.filter((p,i) => i < 1).map(p => Math.ceil(p.died/100)) );
let ancestry2 = ancestry
                  .map( p => (p.century = Math.ceil(p.died/100), p) )
                  .map( p => (p.age = p.died - p.born, p) );

let byCentury = {}
each(ancestry2, p => {
  if(!byCentury[p.century]) byCentury[p.century] = [p];
  else byCentury[p.century].push(p);
});

each(byCentury, people => {
  log('In the %dth hundreds, the average age of %d person(s) was %d', people[0].century, people.length, averageAge(people));
});

function averageAge(list) {
  return average(list.map(p => p.age)).toFixed(2);
}

function each(iterable, fn) {
  if( Array.isArray(iterable) ) iterable.forEach(fn);
  for(let century in iterable)
    fn( iterable[century] );
}<commit_msg>[exercise] 2nd try - HISTORICAL LIFE EXPECTANCY<commit_after>"use strict"

const ancestry = JSON.parse(require("./ancestry"))
const log = console.log;

/* HISTORICAL LIFE EXPECTANCY */
each(groupBy(ancestry, p => Math.ceil(p.died/100)), (people, century) => {
  log('In the %dth hundreds, the average age of %d person(s) was %d', century, people.length, averageAge(people));
});

function each(iterable, fn) {
  if( Array.isArray(iterable) ) return iterable.forEach(fn);
  for(let key in iterable) {
    if(iterable.hasOwnProperty(key)) fn( iterable[key], key, iterable );
  }
}

function groupBy(list, f) {
  let ret = {};
  list.forEach(item => {
    let key = f(item);
    if(Array.isArray(ret[key])) ret[key].push(item);
    else ret[key] = [item];
  });
  return ret;
}

function averageAge(list) {
  return average(list.map(p => p.died - p.born)).toFixed(2);
}

function average(array) {
  let plus = (a,b) => a + b;
  return array.reduce(plus) / array.length
}
{'fraction_non_alphanumeric': 0.18584474885844748, 'fraction_numerical': 0.01004566210045662, 'mean_word_length': 3.7017167381974247, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4210027', 'n_tokens_mistral': 857, 'n_tokens_neox': 814, 'n_words': 191}