1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

fix string comparison functions

This commit is contained in:
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)
}
// s >= a
fn (s string) ge(a string) bool {
mut j := 0
// s < a
fn (s string) lt(a string) bool {
for i := 0; i < s.len; i++ {
if i >= a.len {
return true
}
if int(s[i]) < int(a[j]) {
if i >= a.len || s[i] > a[i] {
return false
}
else if int(s[i]) > int(a[j]) {
else if s[i] < a[i] {
return true
}
j++
}
if s.len < a.len {
return true
}
return false
}
// s <= a
fn (s string) le(a string) bool {
return !s.ge(a) || s == a
}
// s < a
fn (s string) lt(a string) bool {
return s.le(a) && s != a
return s.lt(a) || s.eq(a)
}
// s > a
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.

View File

@ -32,16 +32,59 @@ fn test_compare() {
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() {
mut vals := [
'src', 'Music', 'go'
'arr', 'an', 'a', 'any'
]
len := vals.len
vals.sort()
assert len == vals.len
assert vals[0] == 'Music'
assert vals[1] == 'go'
assert vals[2] == 'src'
assert vals[0] == 'a'
assert vals[1] == 'an'
assert vals[2] == 'any'
assert vals[3] == 'arr'
}
fn test_split() {
@ -247,4 +290,3 @@ fn test_all_after() {
q := s.all_after('fn ')
assert q == 'hello'
}