1 /// Flatmaps a range 2 module ddash.algorithm.flatmap; 3 import ddash.common; 4 5 /// 6 unittest { 7 auto dup(int n) { 8 return [n, n]; 9 } 10 11 assert([1, 2].flatMap!dup.equal([1, 1, 2, 2])); 12 13 import optional: some, no; 14 15 assert([ 16 no!int, 17 some(3), 18 no!int, 19 some(7), 20 ].flatMap!"a".equal( 21 [3, 7] 22 )); 23 } 24 25 /** 26 Flatmaps a range of elemenents 27 28 Params: 29 unaryPred = unary mapping function 30 range = an input range 31 32 Returns: 33 New range that has been mapped and flattened 34 35 Since: 36 0.0.1 37 */ 38 auto flatMap(alias unaryPred, Range)(Range range) if (from!"std.range".isInputRange!Range) { 39 import std.algorithm: map; 40 import ddash.algorithm: flatten; 41 return range 42 .map!unaryPred 43 .flatten; 44 } 45 46 unittest { 47 import optional: some, no; 48 auto optionalArray = [ 49 no!int, 50 some(3), 51 no!int, 52 some(7), 53 ]; 54 assert(optionalArray.flatMap!(a => a).equal([3, 7])); 55 } 56 57 unittest { 58 auto intArray = [ 59 3, 60 7, 61 ]; 62 assert(intArray.flatMap!(a => a).equal([3, 7])); 63 } 64 65 unittest { 66 auto intArrayOfArrays = [ 67 [3], 68 [], 69 [7, 8], 70 [], 71 ]; 72 assert(intArrayOfArrays.flatMap!(a => a).equal([3, 7, 8])); 73 }