glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! List methods, as Ruby's `Enumerable` and Elixir's `Enum` give: on any
//! `Vec`, slice or loaded `has_many`, without `.iter()` or `.collect()`.
//!
//! ```
//! use glacier::prelude::*;
//! let pages = vec![120, 340, 80];
//! assert_eq!(pages.map(|p| p * 2), vec![240, 680, 160]);
//! assert_eq!(pages.filter(|p| *p > 100), vec![120, 340]);
//! assert_eq!(pages.sum(|p| *p), 540);
//! assert_eq!(pages.find(|p| *p < 100), Some(&80));
//! ```
//!
//! In `.glacier`, an atom names a field: `books.map(:title)` is
//! `books.map(fn b -> b.title.clone() end)`.

use std::collections::HashMap;
use std::hash::Hash;

/// See the [module docs](self).
pub trait List<T> {
    /// Each item turned into something else: `books.map(fn b -> b.title end)`.
    fn map<'a, U>(&'a self, f: impl FnMut(&'a T) -> U) -> Vec<U>
    where
        T: 'a;
    /// Each item turned into something else, leaving out the `None`s, as
    /// Ruby's `filter_map`: `books.filter_map(:price)`, the prices that are
    /// set.
    fn filter_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Vec<U>
    where
        T: 'a;
    /// The items `keep` says yes to.
    fn filter(&self, keep: impl FnMut(&T) -> bool) -> Vec<T>
    where
        T: Clone;
    /// The items `drop` says no to.
    fn reject(&self, mut drop: impl FnMut(&T) -> bool) -> Vec<T>
    where
        T: Clone,
    {
        self.filter(|item| !drop(item))
    }
    /// The first item `matches` says yes to.
    fn find(&self, matches: impl FnMut(&T) -> bool) -> Option<&T>;
    /// Whether any item matches.
    fn any(&self, matches: impl FnMut(&T) -> bool) -> bool;
    /// Whether every item matches.
    fn all(&self, matches: impl FnMut(&T) -> bool) -> bool;
    /// How many items match.
    fn count_where(&self, matches: impl FnMut(&T) -> bool) -> usize;
    /// The sum of `f` over the items: `books.sum(fn b -> b.pages end)`
    /// (`books.sum(:pages)` in `.glacier`), as a query's `sum`.
    fn sum<N: std::iter::Sum<N>>(&self, f: impl FnMut(&T) -> N) -> N;
    /// The items sorted by `key`, in a new list (`sort_by` sorts in place).
    fn sorted_by<K: Ord>(&self, key: impl FnMut(&T) -> K) -> Vec<T>
    where
        T: Clone;
    /// The item with the least `key`.
    fn min_by_key<K: Ord>(&self, key: impl FnMut(&T) -> K) -> Option<&T>;
    /// The item with the greatest `key`.
    fn max_by_key<K: Ord>(&self, key: impl FnMut(&T) -> K) -> Option<&T>;
    /// The items in groups by `key`, the groups in the order their first
    /// items come.
    fn group_by<K: Eq + Hash + Clone>(&self, key: impl FnMut(&T) -> K) -> Vec<(K, Vec<T>)>
    where
        T: Clone;
    /// The items with each `key` once, the first of each kept.
    fn uniq_by<K: Eq + Hash>(&self, key: impl FnMut(&T) -> K) -> Vec<T>
    where
        T: Clone;
    /// Runs `f` for each item.
    fn each(&self, f: impl FnMut(&T));
    /// Each item turned into something else by a step that can fail: the
    /// list, or the first error (`rows.try_map(fn r -> r.get("id") end)?`).
    fn try_map<'a, U, E>(&'a self, f: impl FnMut(&'a T) -> Result<U, E>) -> Result<Vec<U>, E>
    where
        T: 'a;
    /// The first `Some` that `f` gives: `rows.find_map(fn r -> r.note end)`.
    fn find_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Option<U>
    where
        T: 'a;
    /// Where the first item `matches` says yes to is, from 0.
    fn position(&self, matches: impl FnMut(&T) -> bool) -> Option<usize>;
    /// Each item with where it is, from 0: `for (i, row) in rows.enumerate()`.
    fn enumerate(&self) -> Vec<(usize, &T)>;
    /// Each item paired with the one at the same place in `other`, as long
    /// as the shorter list.
    fn zip<'a, U>(&'a self, other: &'a [U]) -> Vec<(&'a T, &'a U)>;
    /// The items last to first, in a new list (`reverse` turns a list round
    /// in place).
    fn reversed(&self) -> Vec<T>
    where
        T: Clone;
}

/// `scores.compact()`: the values of a list of `Option`s, without the
/// `None`s, as Ruby's `compact`.
pub trait Compact<T> {
    fn compact(&self) -> Vec<T>;
}

impl<T: Clone> Compact<T> for [Option<T>] {
    fn compact(&self) -> Vec<T> {
        self.iter().flatten().cloned().collect()
    }
}

impl<T> List<T> for [T] {
    fn map<'a, U>(&'a self, f: impl FnMut(&'a T) -> U) -> Vec<U>
    where
        T: 'a,
    {
        self.iter().map(f).collect()
    }

    fn filter_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Vec<U>
    where
        T: 'a,
    {
        self.iter().filter_map(f).collect()
    }

    fn filter(&self, mut keep: impl FnMut(&T) -> bool) -> Vec<T>
    where
        T: Clone,
    {
        self.iter().filter(|item| keep(item)).cloned().collect()
    }

    fn find(&self, mut matches: impl FnMut(&T) -> bool) -> Option<&T> {
        self.iter().find(|item| matches(item))
    }

    fn any(&self, matches: impl FnMut(&T) -> bool) -> bool {
        self.iter().any(matches)
    }

    fn all(&self, matches: impl FnMut(&T) -> bool) -> bool {
        self.iter().all(matches)
    }

    fn count_where(&self, mut matches: impl FnMut(&T) -> bool) -> usize {
        self.iter().filter(|item| matches(item)).count()
    }

    fn sum<N: std::iter::Sum<N>>(&self, f: impl FnMut(&T) -> N) -> N {
        self.iter().map(f).sum()
    }

    fn sorted_by<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Vec<T>
    where
        T: Clone,
    {
        let mut sorted = self.to_vec();
        sorted.sort_by_key(|item| key(item));
        sorted
    }

    fn min_by_key<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Option<&T> {
        self.iter().min_by_key(|item| key(item))
    }

    fn max_by_key<K: Ord>(&self, mut key: impl FnMut(&T) -> K) -> Option<&T> {
        self.iter().max_by_key(|item| key(item))
    }

    fn group_by<K: Eq + Hash + Clone>(&self, mut key: impl FnMut(&T) -> K) -> Vec<(K, Vec<T>)>
    where
        T: Clone,
    {
        let mut groups: Vec<(K, Vec<T>)> = Vec::new();
        let mut at: HashMap<K, usize> = HashMap::new();
        for item in self {
            let k = key(item);
            match at.get(&k) {
                Some(&i) => groups[i].1.push(item.clone()),
                None => {
                    at.insert(k.clone(), groups.len());
                    groups.push((k, vec![item.clone()]));
                }
            }
        }
        groups
    }

    fn uniq_by<K: Eq + Hash>(&self, mut key: impl FnMut(&T) -> K) -> Vec<T>
    where
        T: Clone,
    {
        let mut seen = std::collections::HashSet::new();
        self.iter()
            .filter(|item| seen.insert(key(item)))
            .cloned()
            .collect()
    }

    fn try_map<'a, U, E>(&'a self, f: impl FnMut(&'a T) -> Result<U, E>) -> Result<Vec<U>, E>
    where
        T: 'a,
    {
        self.iter().map(f).collect()
    }

    fn each(&self, f: impl FnMut(&T)) {
        self.iter().for_each(f);
    }

    fn find_map<'a, U>(&'a self, f: impl FnMut(&'a T) -> Option<U>) -> Option<U>
    where
        T: 'a,
    {
        self.iter().find_map(f)
    }

    fn position(&self, matches: impl FnMut(&T) -> bool) -> Option<usize> {
        self.iter().position(matches)
    }

    fn enumerate(&self) -> Vec<(usize, &T)> {
        self.iter().enumerate().collect()
    }

    fn zip<'a, U>(&'a self, other: &'a [U]) -> Vec<(&'a T, &'a U)> {
        self.iter().zip(other).collect()
    }

    fn reversed(&self) -> Vec<T>
    where
        T: Clone,
    {
        self.iter().rev().cloned().collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn lists_read_as_ruby_and_elixir_do() {
        let words: &[&str] = &["pear", "fig", "apple", "plum"];
        assert_eq!(words.map(|w| w.len()), vec![4, 3, 5, 4]);
        assert_eq!(words.reject(|w| w.len() == 4), vec!["fig", "apple"]);
        assert_eq!(
            words.filter_map(|w| w.strip_prefix('p')),
            vec!["ear", "lum"]
        );
        assert!(words.any(|w| w.starts_with('a')));
        assert!(!words.all(|w| w.len() > 3));
        assert_eq!(words.count_where(|w| w.len() == 4), 2);
        assert_eq!(
            words.sorted_by(|w| w.len()),
            vec!["fig", "pear", "plum", "apple"]
        );
        assert_eq!(words.min_by_key(|w| w.len()), Some(&"fig"));
        assert_eq!(
            words.group_by(|w| w.len()),
            vec![
                (4, vec!["pear", "plum"]),
                (3, vec!["fig"]),
                (5, vec!["apple"])
            ]
        );
        assert_eq!(words.uniq_by(|w| w.len()), vec!["pear", "fig", "apple"]);
        let lengths: Result<Vec<usize>, String> = words.try_map(|w| Ok(w.len()));
        assert_eq!(lengths, Ok(vec![4, 3, 5, 4]));
        let failed: Result<Vec<usize>, String> = words.try_map(|w| {
            if w.len() > 4 {
                Err(w.to_string())
            } else {
                Ok(1)
            }
        });
        assert_eq!(failed, Err("apple".to_owned()));
        assert_eq!([Some(1), None, Some(3)].compact(), vec![1, 3]);
        assert_eq!(words.find_map(|w| w.strip_prefix('a')), Some("pple"));
        assert_eq!(words.position(|w| w.len() == 5), Some(2));
        assert_eq!(words.enumerate()[1], (1, &"fig"));
        assert_eq!(words.zip(&[1, 2]), vec![(&"pear", &1), (&"fig", &2)]);
        assert_eq!(words.reversed(), vec!["plum", "apple", "fig", "pear"]);
        // On a `Vec` too, which derefs to the slice.
        let owned: Vec<i32> = Vec::from([3, 1, 2]);
        assert_eq!(owned.position(|n| *n == 1), Some(1));
    }
}