1 /* 2 ------------------------------------------------------------------- 3 4 Copyright (C) 2014, Edwin van Leeuwen 5 6 This file is part of plotd plotting library. 7 8 Plotd is free software; you can redistribute it and/or modify 9 it under the terms of the GNU General Public License as published by 10 the Free Software Foundation; either version 3 of the License, or 11 (at your option) any later version. 12 13 Plotd is distributed in the hope that it will be useful, 14 but WITHOUT ANY WARRANTY; without even the implied warranty of 15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 GNU General Public License for more details. 17 18 You should have received a copy of the GNU General Public License 19 along with Plotd. If not, see <http://www.gnu.org/licenses/>. 20 21 ------------------------------------------------------------------- 22 */ 23 24 module cli.algorithm; 25 26 import std.range : ElementType, isInputRange, front; 27 28 version( unittest ) { 29 import std.stdio : writeln; 30 } 31 32 33 auto groupBy(alias func, R)(R values) 34 if (isInputRange!R) 35 { 36 alias K = typeof(func(values.front)); 37 alias V = ElementType!R[]; 38 V[K] grouped; 39 foreach(value; values) grouped[func(value)] ~= value; 40 return grouped; 41 } 42 43 unittest { 44 struct Test { 45 string a; 46 double b; 47 } 48 49 auto values = [Test( "a", 1 ), Test( "a", 2 ), Test( "b", 3 )]; 50 auto grouped = values.groupBy!( (a) => a.a ); 51 assert( grouped["a"].length == 2 ); 52 assert( grouped["a"][1].b == 2 ); 53 assert( grouped["b"].length == 1 ); 54 assert( grouped["b"][0].b == 3 ); 55 }