Merge pull request #2077 from take-cheeze/rstruct_macro
[mruby.git] / mrbgems / mruby-array-ext / mrblib / array.rb
blob6c47235fe2a085dda7d80ae9322cf7a6a90c9a8c
1 class Array
2   ##
3   # call-seq:
4   #    ary.uniq!                -> ary or nil
5   #    ary.uniq! { |item| ... } -> ary or nil
6   #
7   # Removes duplicate elements from +self+.
8   # Returns <code>nil</code> if no changes are made (that is, no
9   # duplicates are found).
10   #
11   #    a = [ "a", "a", "b", "b", "c" ]
12   #    a.uniq!   #=> ["a", "b", "c"]
13   #    b = [ "a", "b", "c" ]
14   #    b.uniq!   #=> nil
15   #    c = [["student","sam"], ["student","george"], ["teacher","matz"]]
16   #    c.uniq! { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
17   #
18   def uniq!(&block)
19     ary = self.dup
20     result = []
21     if block
22       hash = {}
23       while ary.size > 0
24         val = ary.shift
25         key = block.call(val)
26         hash[key] = val unless hash.has_key?(key)
27       end
28       hash.each_value do |value|
29         result << value
30       end
31     else
32       while ary.size > 0
33         result << ary.shift
34         ary.delete(result.last)
35       end
36     end
37     if result.size == self.size
38       nil
39     else
40       self.replace(result)
41     end
42   end
44   ##
45   # call-seq:
46   #    ary.uniq                -> new_ary
47   #    ary.uniq { |item| ... } -> new_ary
48   #
49   # Returns a new array by removing duplicate values in +self+.
50   #
51   #    a = [ "a", "a", "b", "b", "c" ]
52   #    a.uniq   #=> ["a", "b", "c"]
53   #
54   #    b = [["student","sam"], ["student","george"], ["teacher","matz"]]
55   #    b.uniq { |s| s.first } # => [["student", "sam"], ["teacher", "matz"]]
56   #
57   def uniq(&block)
58     ary = self.dup
59     if block
60       ary.uniq!(&block)
61     else 
62       ary.uniq!
63     end
64     ary
65   end
67   ##
68   # call-seq:
69   #    ary - other_ary    -> new_ary
70   #
71   # Array Difference---Returns a new array that is a copy of
72   # the original array, removing any items that also appear in
73   # <i>other_ary</i>. (If you need set-like behavior, see the
74   # library class Set.)
75   #
76   #    [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]  #=>  [ 3, 3, 5 ]
77   #
78   def -(elem)
79     raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
81     hash = {}
82     array = []
83     elem.each { |x| hash[x] = true }
84     self.each { |x| array << x unless hash[x] }
85     array
86   end
88   ##
89   # call-seq:
90   #    ary | other_ary     -> new_ary
91   #
92   # Set Union---Returns a new array by joining this array with
93   # <i>other_ary</i>, removing duplicates.
94   #
95   #    [ "a", "b", "c" ] | [ "c", "d", "a" ]
96   #           #=> [ "a", "b", "c", "d" ]
97   #
98   def |(elem)
99     raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
101     ary = self + elem
102     ary.uniq! or ary
103   end
105   ##
106   # call-seq:
107   #    ary & other_ary      -> new_ary
108   #
109   # Set Intersection---Returns a new array
110   # containing elements common to the two arrays, with no duplicates.
111   #
112   #    [ 1, 1, 3, 5 ] & [ 1, 2, 3 ]   #=> [ 1, 3 ]
113   #
114   def &(elem)
115     raise TypeError, "can't convert #{elem.class} into Array" unless elem.class == Array
117     hash = {}
118     array = []
119     elem.each{|v| hash[v] = true }
120     self.each do |v|
121       if hash[v]
122         array << v
123         hash.delete v
124       end
125     end
126     array
127   end
129   ##
130   # call-seq:
131   #    ary.flatten -> new_ary
132   #    ary.flatten(level) -> new_ary
133   #
134   # Returns a new array that is a one-dimensional flattening of this
135   # array (recursively). That is, for every element that is an array,
136   # extract its elements into the new array.  If the optional
137   # <i>level</i> argument determines the level of recursion to flatten.
138   #
139   #    s = [ 1, 2, 3 ]           #=> [1, 2, 3]
140   #    t = [ 4, 5, 6, [7, 8] ]   #=> [4, 5, 6, [7, 8]]
141   #    a = [ s, t, 9, 10 ]       #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]
142   #    a.flatten                 #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
143   #    a = [ 1, 2, [3, [4, 5] ] ]
144   #    a.flatten(1)              #=> [1, 2, 3, [4, 5]]
145   #
146   def flatten(depth=nil)
147     ar = []
148     self.each do |e|
149       if e.is_a?(Array) && (depth.nil? || depth > 0)
150         ar += e.flatten(depth.nil? ? nil : depth - 1)
151       else
152         ar << e
153       end
154     end
155     ar
156   end
158   ##
159   # call-seq:
160   #    ary.flatten!        -> ary or nil
161   #    ary.flatten!(level) -> array or nil
162   #
163   # Flattens +self+ in place.
164   # Returns <code>nil</code> if no modifications were made (i.e.,
165   # <i>ary</i> contains no subarrays.)  If the optional <i>level</i>
166   # argument determines the level of recursion to flatten.
167   #
168   #    a = [ 1, 2, [3, [4, 5] ] ]
169   #    a.flatten!   #=> [1, 2, 3, 4, 5]
170   #    a.flatten!   #=> nil
171   #    a            #=> [1, 2, 3, 4, 5]
172   #    a = [ 1, 2, [3, [4, 5] ] ]
173   #    a.flatten!(1) #=> [1, 2, 3, [4, 5]]
174   #
175   def flatten!(depth=nil)
176     modified = false
177     ar = []
178     self.each do |e|
179       if e.is_a?(Array) && (depth.nil? || depth > 0)
180         ar += e.flatten(depth.nil? ? nil : depth - 1)
181         modified = true
182       else
183         ar << e
184       end
185     end
186     if modified
187       self.replace(ar)
188     else
189       nil
190     end
191   end
193   ##
194   # call-seq:
195   #    ary.compact     -> new_ary
196   #
197   # Returns a copy of +self+ with all +nil+ elements removed.
198   #
199   #    [ "a", nil, "b", nil, "c", nil ].compact
200   #                      #=> [ "a", "b", "c" ]
201   #
202   def compact
203     result = self.dup
204     result.compact!
205     result
206   end
208   ##
209   # call-seq:
210   #    ary.compact!    -> ary  or  nil
211   #
212   # Removes +nil+ elements from the array.
213   # Returns +nil+ if no changes were made, otherwise returns
214   # <i>ary</i>.
215   #
216   #    [ "a", nil, "b", nil, "c" ].compact! #=> [ "a", "b", "c" ]
217   #    [ "a", "b", "c" ].compact!           #=> nil
218   #
219   def compact!
220     result = self.select { |e| e != nil }
221     if result.size == self.size
222       nil
223     else
224       self.replace(result)
225     end
226   end
228   # for efficiency
229   def reverse_each(&block)
230     return to_enum :reverse_each unless block_given?
232     i = self.size - 1
233     while i>=0
234       block.call(self[i])
235       i -= 1
236     end
237     self
238   end
240   NONE=Object.new
241   ##
242   #  call-seq:
243   #     ary.fetch(index)                    -> obj
244   #     ary.fetch(index, default)           -> obj
245   #     ary.fetch(index) { |index| block }  -> obj
246   #
247   #  Tries to return the element at position +index+, but throws an IndexError
248   #  exception if the referenced +index+ lies outside of the array bounds.  This
249   #  error can be prevented by supplying a second argument, which will act as a
250   #  +default+ value.
251   #
252   #  Alternatively, if a block is given it will only be executed when an
253   #  invalid +index+ is referenced.  Negative values of +index+ count from the
254   #  end of the array.
255   #
256   #     a = [ 11, 22, 33, 44 ]
257   #     a.fetch(1)               #=> 22
258   #     a.fetch(-1)              #=> 44
259   #     a.fetch(4, 'cat')        #=> "cat"
260   #     a.fetch(100) { |i| puts "#{i} is out of bounds" }
261   #                              #=> "100 is out of bounds"
262   #
264   def fetch(n=nil, ifnone=NONE, &block)
265     warn "block supersedes default value argument" if n != nil && ifnone != NONE && block
267     idx = n
268     if idx < 0
269       idx += size
270     end
271     if idx < 0 || size <= idx
272       return block.call(n) if block
273       if ifnone == NONE
274         raise IndexError, "index #{n} outside of array bounds: #{-size}...#{size}"
275       end
276       return ifnone
277     end
278     self[idx]
279   end
281   ##
282   #  call-seq:
283   #     ary.fill(obj)                                 -> ary
284   #     ary.fill(obj, start [, length])               -> ary
285   #     ary.fill(obj, range )                         -> ary
286   #     ary.fill { |index| block }                    -> ary
287   #     ary.fill(start [, length] ) { |index| block } -> ary
288   #     ary.fill(range) { |index| block }             -> ary
289   #
290   #  The first three forms set the selected elements of +self+ (which
291   #  may be the entire array) to +obj+.
292   #
293   #  A +start+ of +nil+ is equivalent to zero.
294   #
295   #  A +length+ of +nil+ is equivalent to the length of the array.
296   #
297   #  The last three forms fill the array with the value of the given block,
298   #  which is passed the absolute index of each element to be filled.
299   #
300   #  Negative values of +start+ count from the end of the array, where +-1+ is
301   #  the last element.
302   #
303   #     a = [ "a", "b", "c", "d" ]
304   #     a.fill("x")              #=> ["x", "x", "x", "x"]
305   #     a.fill("w", -1)          #=> ["x", "x", "x", "w"]
306   #     a.fill("z", 2, 2)        #=> ["x", "x", "z", "z"]
307   #     a.fill("y", 0..1)        #=> ["y", "y", "z", "z"]
308   #     a.fill { |i| i*i }       #=> [0, 1, 4, 9]
309   #     a.fill(-2) { |i| i*i*i } #=> [0, 1, 8, 27]
310   #     a.fill(1, 2) { |i| i+1 } #=> [0, 2, 3, 27]
311   #     a.fill(0..1) { |i| i+1 } #=> [1, 2, 3, 27]
312   #
314   def fill(arg0=nil, arg1=nil, arg2=nil, &block)
315     if arg0 == nil && arg1 == nil && arg2 == nil && !block
316       raise ArgumentError, "wrong number of arguments (0 for 1..3)" 
317     end
319     beg = len = 0
320     ary = []
321     if block
322       if arg0 == nil && arg1 == nil && arg2 == nil
323         # ary.fill { |index| block }                    -> ary
324         beg = 0
325         len = self.size
326       elsif arg0 != nil && arg0.respond_to?(:begin) && arg0.respond_to?(:end)
327         # ary.fill(range) { |index| block }             -> ary
328         beg = arg0.begin
329         beg += self.size if beg < 0
330         len = arg0.end - beg + 1
331       elsif arg0 != nil
332         # ary.fill(start [, length] ) { |index| block } -> ary
333         beg = arg0
334         beg += self.size if beg < 0
335         if arg1 == nil
336           len = self.size
337         else
338           len = arg0 + arg1
339         end
340       end
341     else
342       if arg0 != nil && arg1 == nil && arg2 == nil
343         # ary.fill(obj)                                 -> ary
344         beg = 0
345         len = self.size      
346       elsif arg0 != nil && arg1 != nil && arg1.respond_to?(:begin) && arg1.respond_to?(:end)
347         # ary.fill(obj, range )                         -> ary
348         len = self.size
349         beg = arg1.begin
350         len = arg1.end - beg + 1
351       elsif arg0 != nil && arg1 != nil
352         # ary.fill(obj, start [, length])               -> ary
353         beg = arg1
354         beg += self.size if beg < 0
355        if arg2 == nil
356           len = self.size
357         else
358           len = arg1 + arg2
359         end
360       end
361     end
363     i = beg
364     if block
365       while i < len
366         self[i] = block.call(i)
367         i += 1
368       end
369     else 
370       while i < len
371         self[i] = arg0
372         i += 1
373       end
374     end
375     self
376   end
378   ##
379   #  call-seq:
380   #     ary.rotate(count=1)    -> new_ary
381   #
382   #  Returns a new array by rotating +self+ so that the element at +count+ is
383   #  the first element of the new array.
384   #
385   #  If +count+ is negative then it rotates in the opposite direction, starting
386   #  from the end of +self+ where +-1+ is the last element.
387   #
388   #     a = [ "a", "b", "c", "d" ]
389   #     a.rotate         #=> ["b", "c", "d", "a"]
390   #     a                #=> ["a", "b", "c", "d"]
391   #     a.rotate(2)      #=> ["c", "d", "a", "b"]
392   #     a.rotate(-3)     #=> ["b", "c", "d", "a"]
394   def rotate(count=1)
395     ary = []
396     len = self.length
398     if len > 0
399       idx = (count < 0) ? (len - (~count % len) - 1) : (count % len) # rotate count
400       len.times do
401         ary << self[idx]
402         idx += 1
403         idx = 0 if idx > len-1
404       end
405     end
406     ary
407   end
409   ##
410   #  call-seq:
411   #     ary.rotate!(count=1)   -> ary
412   #
413   #  Rotates +self+ in place so that the element at +count+ comes first, and
414   #  returns +self+.
415   #
416   #  If +count+ is negative then it rotates in the opposite direction, starting
417   #  from the end of the array where +-1+ is the last element.
418   #
419   #     a = [ "a", "b", "c", "d" ]
420   #     a.rotate!        #=> ["b", "c", "d", "a"]
421   #     a                #=> ["b", "c", "d", "a"]
422   #     a.rotate!(2)     #=> ["d", "a", "b", "c"]
423   #     a.rotate!(-3)    #=> ["a", "b", "c", "d"]
425   def rotate!(count=1)
426     self.replace(self.rotate(count))
427   end