<commit_before>'use strict';
const log = require('../logger'),
  _ = require('lodash'),
  Promise = require('bluebird');

module.exports = function filter(env, matchElements, options) {
  let appIndex = -1;
  _.some(matchElements, (element, index) => {
    if (element.toLowerCase().indexOf('app.') !== -1) {
      appIndex = index;
      return true;
    }
  });
  // If no filter condition is given, return everything in scope
  if (appIndex === -1 || matchElements[appIndex].split('.')[1] === undefined) {
    return Promise.resolve(options.scope);
  }
  const condition = matchElements[appIndex].split('.')[1];
  if (condition.toLowerCase() === 'latest') {
    try {
      const latest = filterByLatest(options.scope);
      return Promise.resolve(latest);
    }
    catch (e) {
      log.error('Failed to apply filter by latest.', e);
      return Promise.reject(e);
    }
  }
};

function filterByLatest(ids) {
  const apps = _.map(ids, (id) => {
      return { n: id.split('-')[0], verc: id.split('-')[1] };
    }),
    packageGroupe = _.groupBy(apps, 'n');
  return _.map(packageGroupe, (val) => {
    const latest = _.max(val, 'verc');
    return latest.n + '-' + latest.verc;
  });
}<commit_msg>refactor<commit_after>'use strict';
const log = require('../logger'),
  _ = require('lodash'),
  Promise = require('bluebird');

module.exports = function filter(env, matchElements, options) {
  const matchByLatest = _.some(matchElements, (element) => {
    if (element.toLowerCase().indexOf('app.latest') > -1) {
      return true;
    }
  });
  // If no "match by latest" filter condition is given, return everything in scope
  if (!matchByLatest) {
    return Promise.resolve(options.scope);
  }
  try {
    const latest = filterByLatest(options.scope);
    return Promise.resolve(latest);
  }
  catch (e) {
    log.error('Failed to apply filter by latest.', e);
    return Promise.reject(e);
  }
};

function filterByLatest(ids) {
  const apps = _.map(ids, (id) => {
      return { n: id.split('-')[0], verc: id.split('-')[1] };
    }),
    groupedAppVersions = _.groupBy(apps, 'n');
  return _.map(groupedAppVersions, (appVersion) => {
    const latest = _.max(appVersion, 'verc');
    return latest.n + '-' + latest.verc;
  });
}
{'fraction_non_alphanumeric': 0.18080357142857142, 'fraction_numerical': 0.004464285714285714, 'mean_word_length': 3.3096153846153844, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 10, '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': '2061253', 'n_tokens_mistral': 733, 'n_tokens_neox': 735, 'n_words': 170}