/
variable.rb
64 lines (51 loc) · 1.5 KB
/
variable.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
module Phony
module NationalSplitters
class Variable < Fixed
#
#
def initialize fallback, ndc_map
super fallback
@ndcs = restructure ndc_map
end
# Takes a national number and splits it into ndc and rest.
#
def split national_number
fallback_number = national_number.dup
# Extract a starting point.
#
presumed_code = if @mapped_ndc_min_length > 0
national_number.slice!(0..@mapped_ndc_min_length-1)
else
''
end
# Try for all possible mapped.
#
@mapped_ndc_min_length.upto(@mapped_ndc_max_length) do |i|
sized_ndcs = @ndcs[i]
return [presumed_code, national_number] unless sized_ndcs && !sized_ndcs.include?(presumed_code)
presumed_code << national_number.slice!(0..0)
end
# Not found.
#
return super(fallback_number)
end
private
def restructure ndc_map
optimize ndc_map.values.flatten
end
# Optimizes and restructures the given ndcs array.
#
def optimize(ndc_ary)
ndcs = {}
ndc_ary.each do |ndc|
ndcs[ndc.length] ||= []
ndcs[ndc.length] << ndc
end
keys = ndcs.keys
@mapped_ndc_min_length = keys.min # || 1
@mapped_ndc_max_length = keys.max
ndcs
end
end
end
end