I have successfully implemented a sorting algorithm in Swift for iOS. (see code below).
Now, I would like to implement the same algo in Dart for Flutter.
And I had to realise that my trial (see below) does not do the same as the Swift code. Why ????
Can anybody explain the difference between Swift's sorted function and Dart's sort function ? Why is my below code-snippets not doing the same in Swift and Dart ???
Here is the Swift code:
return stationItems.sorted {
let nameA = $0.name!
.replacingOccurrences(of: ",", with: "", options: .literal, range: nil)
.replacingOccurrences(of: "ä", with: "a", options: .literal, range: nil)
.replacingOccurrences(of: "ö", with: "o", options: .literal, range: nil)
.replacingOccurrences(of: "ü", with: "u", options: .literal, range: nil)
.lowercased()
let nameB = $1.name!
.replacingOccurrences(of: ",", with: "", options: .literal, range: nil)
.replacingOccurrences(of: "ä", with: "a", options: .literal, range: nil)
.replacingOccurrences(of: "ö", with: "o", options: .literal, range: nil)
.replacingOccurrences(of: "ü", with: "u", options: .literal, range: nil)
.lowercased()
let searchTermy = searchTerm
.replacingOccurrences(of: ",", with: "", options: .literal, range: nil)
.replacingOccurrences(of: "ä", with: "a", options: .literal, range: nil)
.replacingOccurrences(of: "ö", with: "o", options: .literal, range: nil)
.replacingOccurrences(of: "ü", with: "u", options: .literal, range: nil)
.lowercased()
if nameA == searchTermy && nameB != searchTermy {
return true
} else if nameA.hasPrefix(searchTermy) && !nameB.hasPrefix(searchTermy) {
return true
} else if nameA.contains(searchTermy) && !nameB.contains(searchTermy) {
return true
} else {
let n = searchTermy.count
for i in 0..<searchTermy.count {
if nameA.hasPrefix(String(searchTermy[..<(n-i)])) && !nameB.hasPrefix(String(searchTermy[..<(n-i)])) {
return true
} else {
return false
}
}
return false
}
}
Here is the Dart code:
return stationList.sort((a, b) {
var nameA = a.stopName
.replaceAll(RegExp(','), '')
.replaceAll(RegExp('ä'), 'a')
.replaceAll(RegExp('ö'), 'o')
.replaceAll(RegExp('ü'), 'u')
.toLowerCase();
var nameB = b.stopName
.replaceAll(RegExp(','), '')
.replaceAll(RegExp('ä'), 'a')
.replaceAll(RegExp('ö'), 'o')
.replaceAll(RegExp('ü'), 'u')
.toLowerCase();
var searchTermy = stationName
.replaceAll(RegExp(','), '')
.replaceAll(RegExp('ä'), 'a')
.replaceAll(RegExp('ö'), 'o')
.replaceAll(RegExp('ü'), 'u')
.toLowerCase();
if ((nameA == searchTermy) && (nameB != searchTermy)) {
return 1;
} else if (nameA.startsWith(searchTermy) && !nameB.startsWith(searchTermy)) {
return 1;
} else if (nameA.contains(searchTermy) && !nameB.contains(searchTermy)) {
return 1;
} else {
var n = searchTermy.length;
for (int i = 0; i < searchTermy.length; i++) {
if (nameA.startsWith(searchTermy.substring(0, (n - i))) && !nameB.startsWith(searchTermy.substring(0, (n - i)))) {
return 1;
} else {
return 0;
}
}
return 0;
}
});