array-window 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (2) hide show
  1. data/lib/array/window.rb +33 -0
  2. metadata +47 -0
@@ -0,0 +1,33 @@
1
+ class Array
2
+ def window(size, center, even_size_resolution=:prioritize_greater)
3
+ return [] if size <= 0
4
+ return [self[center]] if size == 1
5
+ return self if size >= self.length
6
+
7
+ closest_limit = ->(size, index) {
8
+ return 0 if index < 0
9
+ return size - 1 if index >= size
10
+ index }
11
+ array_closest_limit = closest_limit.curry[self.length]
12
+
13
+ center = array_closest_limit[center]
14
+
15
+ lower = array_closest_limit[center - size/2]
16
+ upper = array_closest_limit[center + size/2]
17
+ while (lower..upper).count < size
18
+ lower = array_closest_limit[lower - 1]
19
+ upper = array_closest_limit[upper + 1]
20
+ end
21
+
22
+ return self.slice(lower..upper) if (lower..upper).count == size
23
+
24
+ case even_size_resolution
25
+ when :prioritize_greater
26
+ return self.slice((lower + 1)..upper)
27
+ when :prioritize_lower
28
+ return self.slice(lower..(upper - 1))
29
+ else
30
+ raise ArgumentError, "#{even_size_resolution} is not a known resolution mechanism"
31
+ end
32
+ end
33
+ end
metadata ADDED
@@ -0,0 +1,47 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: array-window
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Alfonso Cora
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-06-24 00:00:00.000000000 Z
13
+ dependencies: []
14
+ description: Adds the 'window' method to the array class, to allow retrieving a window
15
+ of elements with a specified center and a size
16
+ email: acora6@gmail.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - lib/array/window.rb
22
+ homepage: http://github.com/alfonsocora/array-window
23
+ licenses: []
24
+ post_install_message:
25
+ rdoc_options: []
26
+ require_paths:
27
+ - lib
28
+ required_ruby_version: !ruby/object:Gem::Requirement
29
+ none: false
30
+ requirements:
31
+ - - ! '>='
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ required_rubygems_version: !ruby/object:Gem::Requirement
35
+ none: false
36
+ requirements:
37
+ - - ! '>='
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ requirements: []
41
+ rubyforge_project:
42
+ rubygems_version: 1.8.24
43
+ signing_key:
44
+ specification_version: 3
45
+ summary: Adds the 'window' method to the array class, to allow retrieving a window
46
+ of elements with a specified center and a size
47
+ test_files: []