Skip to main content

oxc_ecmascript/
string_char_code_at.rs

1use crate::{StringCharAt, string_char_at::StringCharAtResult};
2
3pub trait StringCharCodeAt {
4    /// `String.prototype.charCodeAt ( pos )`
5    /// <https://tc39.es/ecma262/#sec-string.prototype.charcodeat>
6    fn char_code_at(&self, index: Option<f64>) -> Option<u32>;
7}
8
9impl StringCharCodeAt for &str {
10    fn char_code_at(&self, index: Option<f64>) -> Option<u32> {
11        match self.char_at(index) {
12            StringCharAtResult::Value(c) => Some(c as u32),
13            StringCharAtResult::InvalidChar(v) => Some(u32::from(v)),
14            StringCharAtResult::OutOfRange => None,
15        }
16    }
17}
18
19#[cfg(test)]
20mod test {
21    use super::StringCharCodeAt;
22
23    #[test]
24    fn test_evaluate_char_code_at() {
25        let s = "abcde";
26        assert_eq!(s.char_code_at(Some(0.0)), Some(97));
27        assert_eq!(s.char_code_at(Some(1.0)), Some(98));
28        assert_eq!(s.char_code_at(Some(2.0)), Some(99));
29        assert_eq!(s.char_code_at(Some(3.0)), Some(100));
30        assert_eq!(s.char_code_at(Some(4.0)), Some(101));
31        assert_eq!(s.char_code_at(Some(5.0)), None);
32        assert_eq!(s.char_code_at(Some(-1.0)), None);
33        assert_eq!(s.char_code_at(None), Some(97));
34        assert_eq!(s.char_code_at(Some(0.0)), Some(97));
35        assert_eq!(s.char_code_at(Some(f64::NAN)), Some(97));
36        assert_eq!(s.char_code_at(Some(f64::INFINITY)), None);
37    }
38}