Skip to content

Instantly share code, notes, and snippets.

@dahu
Created April 20, 2012 09:20
Show Gist options
  • Save dahu/2427305 to your computer and use it in GitHub Desktop.
Save dahu/2427305 to your computer and use it in GitHub Desktop.
Houl's UniqMap
" Original Code by Houl
" Refactored by Barry Arthur, 20 Apr 2012
" UniqMapFirst({list}, {map-expr})
"
" Remove duplicates from {list}, after applying {map-expr} (see :h map()).
" The instance with the lowest index is kept.
"
function! UniqMapFirst(list, mapexpr) "{{{
let mlist = map(copy(a:list), a:mapexpr)
let idx = len(a:list) - 1
while idx >= 1
if index(mlist, mlist[idx]) < idx
call remove(a:list, idx)
endif
let idx -= 1
endwhile
return a:list
endfunction "}}}
" UniqMapLast({list}, {map-expr})
"
" Remove duplicates from {list}, after applying {map-expr} (see :h map()).
" The instance with the highest index is kept.
"
function! UniqMapLast(list, mapexpr) "{{{
return reverse(UniqMapFirst(reverse(a:list), a:mapexpr))
endfunction "}}}
" UniqMap({list}, {map-expr}[, {keep-last}])
"
" Remove duplicates from {list}, after applying {map-expr} (see :h map()).
" The instance with the lowest index is kept, unless {keep-last} is non-zero.
"
function! UniqMap(list, mapexpr, ...) "{{{
(a:0 >= 1 && a:1) ? return UniqMapLast(a:list, a:mapexpr) : return UniqMapFirst(a:list, a:mapexpr)
endfunction "}}}
" test
let data = [['a', 1, 'x'], ['a', 1, 'y'], ['a', 1, 'z'],
\ ['b', 2, 'y'], ['b', 2, 'z'], ['b', 1, 'x'],
\ ['c', 3, 'z'], ['c', 3, 'x'], ['c', 1, 'y']]
echo (UniqMapFirst(copy(data), 'v:val[1]') == [['a', 1, 'x'], ['b', 2, 'y'], ['c', 3, 'z']]) ? "pass" : "fail"
echo ( UniqMapLast(copy(data), 'v:val[1]') == [['b', 2, 'z'], ['c', 3, 'x'], ['c', 1, 'y']]) ? "pass" : "fail"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment