Advertisement
zinch

flatten list

Aug 13th, 2015
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 0.63 KB | None | 0 0
  1.  
  2. def flatten(xs) {
  3.     xs = xs?:[]
  4.     def orig_list = new LinkedList(xs)
  5.     def flat_list = []
  6.  
  7.     while (orig_list) {
  8.         def elem = orig_list.pollFirst()
  9.         switch (elem) {
  10.             case List:
  11.                 elem.reverseEach { orig_list.offerFirst(it) }
  12.                 break
  13.             default:
  14.                 flat_list << elem
  15.         }  
  16.     }
  17.     flat_list
  18. }
  19.  
  20. def original = [[1,2,[3]],4]
  21.  
  22. assert flatten(original) == [1, 2, 3, 4]
  23. assert flatten([]) == []
  24. assert flatten([[[]],[[[]]],[]]) == []
  25. assert flatten([0]) == [0]
  26. assert flatten([0, [null]]) == [0, null]
  27. assert flatten(null) == []
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement