Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand All @@ -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`.



26 changes: 23 additions & 3 deletions src/Data/String/Unsafe.purs
Original file line number Diff line number Diff line change
@@ -1,31 +1,51 @@
-- | Unsafe string and character functions.
module Data.String.Unsafe
( charAt
( char
, charAt
, charCodeAt
) where

import Data.Char

-- | 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);
};
}
""" :: Number -> String -> Number

-- | 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