fix string comparison functions

pull/480/head
Alvydas Vitkauskas 2019-06-23 21:25:50 +03:00 committed by Alex Medvednikov
parent 57466f7960
commit 00594462c4
2 changed files with 63 additions and 23 deletions

View File

@ -169,37 +169,35 @@ fn (s string) ne(a string) bool {
return !s.eq(a) return !s.eq(a)
} }
// s >= a // s < a
fn (s string) ge(a string) bool { fn (s string) lt(a string) bool {
mut j := 0
for i := 0; i < s.len; i++ { for i := 0; i < s.len; i++ {
if i >= a.len { if i >= a.len || s[i] > a[i] {
return true
}
if int(s[i]) < int(a[j]) {
return false return false
} }
else if int(s[i]) > int(a[j]) { else if s[i] < a[i] {
return true return true
} }
j++
} }
return true if s.len < a.len {
return true
}
return false
} }
// s <= a // s <= a
fn (s string) le(a string) bool { fn (s string) le(a string) bool {
return !s.ge(a) || s == a return s.lt(a) || s.eq(a)
}
// s < a
fn (s string) lt(a string) bool {
return s.le(a) && s != a
} }
// s > a // s > a
fn (s string) gt(a string) bool { fn (s string) gt(a string) bool {
return s.ge(a) && s != a return !s.le(a)
}
// s >= a
fn (s string) ge(a string) bool {
return !s.lt(a)
} }
// TODO `fn (s string) + (a string)` ? To be consistent with operator overloading syntax. // TODO `fn (s string) + (a string)` ? To be consistent with operator overloading syntax.

View File

@ -32,16 +32,59 @@ fn test_compare() {
assert b.ge(a) assert b.ge(a)
} }
fn test_lt() {
a := ''
b := 'a'
c := 'a'
d := 'b'
e := 'aa'
f := 'ab'
assert a.lt(b)
assert b.lt(c) == false
assert c.lt(d)
assert d.lt(e) == false
assert c.lt(e)
assert e.lt(f)
}
fn test_ge() {
a := 'aa'
b := 'aa'
c := 'ab'
d := 'abc'
e := 'aaa'
assert b.ge(a)
assert c.ge(b)
assert d.ge(c)
assert c.ge(d) == false
assert e.ge(a)
}
fn test_compare_strings() {
a := 'aa'
b := 'aa'
c := 'ab'
d := 'abc'
e := 'aaa'
assert compare_strings(a, b) == 0
assert compare_strings(b, c) == -1
assert compare_strings(c, d) == -1
assert compare_strings(d, e) == 1
assert compare_strings(a, e) == -1
assert compare_strings(e, a) == 1
}
fn test_sort() { fn test_sort() {
mut vals := [ mut vals := [
'src', 'Music', 'go' 'arr', 'an', 'a', 'any'
] ]
len := vals.len len := vals.len
vals.sort() vals.sort()
assert len == vals.len assert len == vals.len
assert vals[0] == 'Music' assert vals[0] == 'a'
assert vals[1] == 'go' assert vals[1] == 'an'
assert vals[2] == 'src' assert vals[2] == 'any'
assert vals[3] == 'arr'
} }
fn test_split() { fn test_split() {
@ -246,5 +289,4 @@ fn test_all_after() {
s := 'fn hello' s := 'fn hello'
q := s.all_after('fn ') q := s.all_after('fn ')
assert q == 'hello' assert q == 'hello'
} }