Skip to content

Commit

Permalink
Add Hash#last_key and Hash#last_value (#5760)
Browse files Browse the repository at this point in the history
  • Loading branch information
j8r authored and RX14 committed Apr 7, 2018
1 parent 7d64756 commit 3138b52
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
10 changes: 10 additions & 0 deletions spec/std/hash_spec.cr
Expand Up @@ -482,6 +482,16 @@ describe "Hash" do
h.first_value.should eq(2)
end

it "gets last key" do
h = {1 => 2, 3 => 4}
h.last_key.should eq(3)
end

it "gets last value" do
h = {1 => 2, 3 => 4}
h.last_value.should eq(4)
end

it "shifts" do
h = {1 => 2, 3 => 4}
h.shift.should eq({1, 2})
Expand Down
47 changes: 44 additions & 3 deletions src/hash.cr
Expand Up @@ -612,8 +612,8 @@ class Hash(K, V)
# Returns the first key if it exists, or returns `nil`.
#
# ```
# hash = {"foo" => "bar"}
# hash.first_key? # => "foo"
# hash = {"foo1" => "bar1", "foz2" => "baz2"}
# hash.first_key? # => "foo1"
# hash.clear
# hash.first_key? # => nil
# ```
Expand All @@ -626,11 +626,52 @@ class Hash(K, V)
@first.not_nil!.value
end

# Similar to `#first_key?`, but returns its value.
# Returns the first value if it exists, or returns `nil`.
#
# ```
# hash = {"foo1" => "bar1", "foz2" => "baz2"}
# hash.first_value? # => "bar1"
# hash.clear
# hash.first_value? # => nil
# ```
def first_value?
@first.try &.value
end

# Returns the last key in the hash.
def last_key
@last.not_nil!.key
end

# Returns the last key if it exists, or returns `nil`.
#
# ```
# hash = {"foo1" => "bar1", "foz2" => "baz2"}
# hash.last_key? # => "foz2"
# hash.clear
# hash.last_key? # => nil
# ```
def last_key?
@last.try &.key
end

# Returns the last value in the hash.
def last_value
@last.not_nil!.value
end

# Returns the last value if it exists, or returns `nil`.
#
# ```
# hash = {"foo1" => "bar1", "foz2" => "baz2"}
# hash.last_value? # => "baz2"
# hash.clear
# hash.last_value? # => nil
# ```
def last_value?
@last.try &.value
end

# Deletes and returns the first key-value pair in the hash,
# or raises `IndexError` if the hash is empty.
#
Expand Down

0 comments on commit 3138b52

Please sign in to comment.