1 /** 2 Returns a newly allocated associative array from pairs 3 */ 4 module ddash.algorithm.frompairs; 5 6 /// 7 unittest { 8 import std.typecons; 9 assert([tuple(1, 2), tuple(3, 4) ].fromPairs == [1: 2, 3: 4]); 10 } 11 12 import ddash.common; 13 14 /** 15 Returns a newly allocated associative array from pairs 16 17 This is primarily for `std.typecons.Tuple` type objects and works on a range 18 of tuples of size 2. If any other range is given to it, then it will treat 19 every pair of elements as a Tuple and do the same thing. 20 21 Params: 22 r1 = range of elements to create an associated array out of 23 24 Returns: 25 Associative array 26 27 Since: 28 0.0.1 29 */ 30 auto fromPairs(R1)(R1 r1) if (from!"std.range".isInputRange!R1) { 31 import std.range: ElementType; 32 import std.typecons: Tuple; 33 static if (is(ElementType!R1 : Tuple!Args, Args...) && Args.length == 2) 34 { 35 import std.array: assocArray; 36 return r1.assocArray; 37 } 38 else 39 { 40 alias E = ElementType!R1; 41 import std.range; 42 import std.algorithm; 43 return r1.chunks(2).fold!((memo, pair) { 44 auto k = pair.front; 45 pair.popFront; 46 if (!pair.empty) { 47 memo[k] = pair.front; 48 } 49 return memo; 50 })((E[E]).init); 51 } 52 } 53 54 unittest { 55 import std.algorithm: filter; 56 import std.typecons; 57 assert([1, 2, 3].filter!"true".fromPairs == [1: 2]); 58 assert([tuple(1, 2)].fromPairs == [1: 2]); 59 }