Skip to content
This repository was archived by the owner on Nov 8, 2022. It is now read-only.

Commit 414b9e7

Browse files
committed
feat(utils): add str_occurence method
1 parent 82bed1b commit 414b9e7

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

lib/helper/utils.ex

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,4 +237,13 @@ defmodule Helper.Utils do
237237
defp update_word_count(word, acc) do
238238
Map.update(acc, to_string(word), 1, &(&1 + 1))
239239
end
240+
241+
# see https://stackoverflow.com/a/49558074/4050784
242+
@spec str_occurence(String.t(), String.t()) :: Integer.t()
243+
def str_occurence(string, substr) when is_binary(string) and is_binary(substr) do
244+
len = string |> String.split(substr) |> length()
245+
len - 1
246+
end
247+
248+
def str_occurence(_, _), do: "must be strings"
240249
end

test/helper/utils_test.exs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -91,34 +91,41 @@ defmodule GroupherServer.Test.Helper.UtilsTest do
9191
end
9292

9393
describe "[deep merge]" do
94-
test 'one level of maps without conflict' do
94+
test "one level of maps without conflict" do
9595
result = Utils.deep_merge(%{a: 1}, %{b: 2})
9696
assert result == %{a: 1, b: 2}
9797
end
9898

99-
test 'two levels of maps without conflict' do
99+
test "two levels of maps without conflict" do
100100
result = Utils.deep_merge(%{a: %{b: 1}}, %{a: %{c: 3}})
101101
assert result == %{a: %{b: 1, c: 3}}
102102
end
103103

104-
test 'three levels of maps without conflict' do
104+
test "three levels of maps without conflict" do
105105
result = Utils.deep_merge(%{a: %{b: %{c: 1}}}, %{a: %{b: %{d: 2}}})
106106
assert result == %{a: %{b: %{c: 1, d: 2}}}
107107
end
108108

109-
test 'non-map value in left' do
109+
test "non-map value in left" do
110110
result = Utils.deep_merge(%{a: 1}, %{a: %{b: 2}})
111111
assert result == %{a: %{b: 2}}
112112
end
113113

114-
test 'non-map value in right' do
114+
test "non-map value in right" do
115115
result = Utils.deep_merge(%{a: %{b: 1}}, %{a: 2})
116116
assert result == %{a: 2}
117117
end
118118

119-
test 'non-map value in both' do
119+
test "non-map value in both" do
120120
result = Utils.deep_merge(%{a: 1}, %{a: 2})
121121
assert result == %{a: 2}
122122
end
123123
end
124+
125+
describe "[sub str occurence]" do
126+
test "normal occurence case" do
127+
assert 2 == Utils.str_occurence("foo bar foobar", "foo")
128+
assert 0 == Utils.str_occurence("hello world", "foo")
129+
end
130+
end
124131
end

0 commit comments

Comments
 (0)