Skip to content

Commit 36671cb

Browse files
authored
Modify integer conversion for Ruby library (#693)
* Modify integer conversion for Ruby library * fixing rubocop offenses
1 parent cda80c0 commit 36671cb

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

ruby/lib/plus_codes/open_location_code.rb

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -48,23 +48,31 @@ def encode(latitude, longitude, code_length = PAIR_CODE_LENGTH)
4848
end
4949

5050
code_length = MAX_CODE_LENGTH if code_length > MAX_CODE_LENGTH
51-
latitude = clip_latitude(latitude)
52-
longitude = normalize_longitude(longitude)
53-
latitude -= precision_by_length(code_length) if latitude == 90
54-
55-
code = ''
5651

5752
# Compute the code.
5853
# This approach converts each value to an integer after multiplying it by
5954
# the final precision. This allows us to use only integer operations, so
6055
# avoiding any accumulation of floating point representation errors.
61-
lat_val = 90 * PAIR_CODE_PRECISION * LAT_GRID_PRECISION
62-
lat_val += latitude * PAIR_CODE_PRECISION * LAT_GRID_PRECISION
63-
lng_val = 180 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION
64-
lng_val += longitude * PAIR_CODE_PRECISION * LNG_GRID_PRECISION
65-
lat_val = lat_val.to_i
66-
lng_val = lng_val.to_i
56+
lat_val = (latitude * PAIR_CODE_PRECISION * LAT_GRID_PRECISION).round
57+
lat_val += 90 * PAIR_CODE_PRECISION * LAT_GRID_PRECISION
58+
if lat_val.negative?
59+
lat_val = 0
60+
elsif lat_val >= 2 * 90 * PAIR_CODE_PRECISION * LAT_GRID_PRECISION
61+
lat_val = 2 * 90 * PAIR_CODE_PRECISION * LAT_GRID_PRECISION - 1
62+
end
63+
lng_val = (longitude * PAIR_CODE_PRECISION * LNG_GRID_PRECISION).round
64+
lng_val += 180 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION
65+
if lng_val.negative?
66+
# Ruby's % operator differs from other languages in that it returns
67+
# the same sign as the divisor. This means we don't need to add the
68+
# range to the result.
69+
lng_val %= (360 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION)
70+
elsif lng_val >= 360 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION
71+
lng_val %= (360 * PAIR_CODE_PRECISION * LNG_GRID_PRECISION)
72+
end
6773

74+
# Initialise the code string.
75+
code = ''
6876
# Compute the grid part of the code if necessary.
6977
if code_length > PAIR_CODE_LENGTH
7078
(0..MAX_CODE_LENGTH - PAIR_CODE_LENGTH - 1).each do

0 commit comments

Comments
 (0)