1 /**
2 Copyright: Copyright (c) 2016, Joakim Brännström. All rights reserved.
3 License: MPL-2
4 Author: Joakim Brännström (joakim.brannstrom@gmx.com)
5 
6 This Source Code Form is subject to the terms of the Mozilla Public License,
7 v.2.0. If a copy of the MPL was not distributed with this file, You can obtain
8 one at http://mozilla.org/MPL/2.0/.
9 */
10 module cpptooling.utility.dedup;
11 
12 /// Return: sorted and deduplicated array of the range.
13 ///TODO can it be implemented more efficient?
14 auto dedup(T)(T[] arr) {
15     import std.algorithm : makeIndex, uniq, map;
16 
17     auto index = new size_t[arr.length];
18     // sorting the indexes
19     makeIndex(arr, index);
20 
21     // dfmt off
22     return index
23         // dedup the sorted index
24         .uniq!((a,b) => arr[a] == arr[b])
25         // reconstruct an array from the sorted indexes
26         .map!(a => arr[a]);
27     // dfmt on
28 }
29 
30 @safe unittest {
31     import std.array : array;
32 
33     string[] s = ["a", "b", "a"];
34     auto r = s.dedup.array();
35 
36     assert(r == ["a", "b"]);
37 }