Skip to content

Commit ac61e7a

Browse files
authored
Add Set#map! (#16271)
1 parent f5240c3 commit ac61e7a

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

spec/std/set_spec.cr

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,22 @@ describe "Set" do
426426
end
427427
end
428428

429+
describe "#map!" do
430+
it "replaces elements with the block's return values" do
431+
set = Set{1, 2, 3}
432+
set.map! { |n| n * -1 }.should be(set)
433+
set.should eq(Set{-1, -2, -3})
434+
end
435+
436+
it "exhibits reference semantic" do
437+
set = Set{1, 2, 3}
438+
copy = set
439+
440+
set.map! { |n| n * -1 }
441+
set.should eq(copy)
442+
end
443+
end
444+
429445
describe "#select!" do
430446
it "keeps only elements that evaluate to true" do
431447
set = Set{1, 2, 3}

src/set.cr

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,15 @@ struct Set(T)
494494
@hash.same?(other.@hash)
495495
end
496496

497+
# Replaces every element of the set with a value returned from the block, and
498+
# returns `self`.
499+
def map!(& : T -> T) : self
500+
hash = @hash.transform_keys { |k, _| yield(k) }
501+
@hash.clear
502+
@hash.merge!(hash)
503+
self
504+
end
505+
497506
# Deletes every element of the set for which the block is falsey, and returns
498507
# `self`.
499508
def select!(& : T ->) : self

0 commit comments

Comments
 (0)