aboutsummaryrefslogtreecommitdiff
path: root/src/str.gleam
blob: 8aa3e29ea29bfec31ba06dd6a294dfceb12ce82c (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Named str to avoid name collisions with the Erlang string module.
// Will rename later once we have namespaces for modules.

import expect
import iodata
import list

pub external fn length(String) -> Int = "string" "length"

test length {
  length("ß↑e̊")
  |> expect:equal(_, 3)

  length("Gleam")
  |> expect:equal(_, 5)

  length("")
  |> expect:equal(_, 0)

  // TODO: This crashes.
  // length("é")
  // |> expect:equal(_, 1)
}

pub external fn lowercase(String) -> String = "string" "lowercase"

test lowercase {
  lowercase("Gleam")
  |> expect:equal(_, "gleam")
}

pub external fn uppercase(String) -> String = "string" "uppercase"

test uppercase {
  uppercase("Gleam")
  |> expect:equal(_, "GLEAM")
}

pub fn reverse(string) {
  string
  |> iodata:new
  |> iodata:reverse
  |> iodata:to_string
}

test reverse {
  reverse("Gleam")
  |> expect:equal(_, "maelG")
}

pub fn split(string, on) {
  string
  |> iodata:new
  |> iodata:split(_, on)
  |> list:map(_, iodata:to_string)
}

test split {
  "Gleam,Erlang,Elixir"
  |> split(_, ",")
  |> expect:equal(_, ["Gleam", "Erlang", "Elixir"])

  "Gleam, Erlang,Elixir"
  |> split(_, ", ")
  |> expect:equal(_, ["Gleam", "Erlang,Elixir"])
}

pub fn replace(string, pattern, with) {
  string
  |> iodata:new
  |> iodata:replace(_, pattern, with)
  |> iodata:to_string
}

test replace {
  "Gleam,Erlang,Elixir"
  |> replace(_, ",", "++")
  |> expect:equal(_, "Gleam++Erlang++Elixir")
}