diff --git a/README.md b/README.md index 31504b7..4545e05 100644 --- a/README.md +++ b/README.md @@ -434,7 +434,7 @@ charCodeAt :: Number -> String -> Number Returns the numeric Unicode value of the character at the given index. -**Unsafe:** returns `NaN` if the index is out of bounds. +**Unsafe:** throws runtime exception if the index is out of bounds. #### `charAt` @@ -444,7 +444,17 @@ charAt :: Number -> String -> Char Returns the character at the given index. -**Unsafe:** returns an illegal value if the index is out of bounds. +**Unsafe:** throws runtime exception if the index is out of bounds. + +#### `char` + +``` purescript +char :: String -> Char +``` + +Converts a string of length `1` to a character. + +**Unsafe:** throws runtime exception if length is not `1`. diff --git a/src/Data/String/Unsafe.purs b/src/Data/String/Unsafe.purs index c31cba7..547f002 100644 --- a/src/Data/String/Unsafe.purs +++ b/src/Data/String/Unsafe.purs @@ -1,6 +1,7 @@ -- | Unsafe string and character functions. module Data.String.Unsafe - ( charAt + ( char + , charAt , charCodeAt ) where @@ -8,11 +9,14 @@ module Data.String.Unsafe -- | Returns the numeric Unicode value of the character at the given index. -- | - -- | **Unsafe:** returns `NaN` if the index is out of bounds. + -- | **Unsafe:** throws runtime exception if the index is out of bounds. foreign import charCodeAt """ function charCodeAt(i) { return function(s) { + if (s.length <= i) { + throw new Error("Data.String.Unsafe.charCodeAt: Invalid index."); + }; return s.charCodeAt(i); }; } @@ -20,12 +24,28 @@ module Data.String.Unsafe -- | Returns the character at the given index. -- | - -- | **Unsafe:** returns an illegal value if the index is out of bounds. + -- | **Unsafe:** throws runtime exception if the index is out of bounds. foreign import charAt """ function charAt(i) { return function(s) { + if (s.length <= i) { + throw new Error("Data.String.Unsafe.charAt: Invalid index."); + }; return s.charAt(i); }; } """ :: Number -> String -> Char + + -- | Converts a string of length `1` to a character. + -- | + -- | **Unsafe:** throws runtime exception if length is not `1`. + foreign import char + """ + function $$char(s) { + if (s.length != 1) { + throw new Error("Data.String.Unsafe.char: Expected string of length 1."); + }; + return s.charAt(0); + } + """ :: String -> Char