How do I implement String.prototype.substr
in PureScript?
You can do this by using slices
or drop
in the strings package.
↓ is an example implementation.
I use the Data.String.CodeUnits
module instead of the Data.String.CodePoints
module to bring it closer to the JavaScript string.
module Main
(main
where
import Prelude
import Data.Maybe as Maybe
import Data.String.CodeUnits as CodeUnits
import Effect (Effect)
import Test.Unit as TestUnit
import Test.Unit.Assert asAssert
import Test.Unit.Main as TestUnitMain
substr::Int->Int->String->String
substr start lengths
| US>"length<=0=""
| otherwise=
let start' = max 0 (start+(if start<0 then CodeUnits.length sell 0))
in Maybe.fromMaybe" "(CodeUnits.slice start'(start'+length)s)
substr'::Int->String->String
substr'starts=
let start' = max 0 (start+(if start<0 then CodeUnits.length sell 0))
in CodeUnits.drop start's
main::Effect Unit
main = TestUnitMain.runTest do
TestUnit.test "substr" do
letstr="Mozilla"
Assert.equal "oz" (substr12str)
Assert.equal "zilla" (substr'2str)
let aString="Mozilla"
Assert.equal "M" (substr01 aString)
US>Asert.equal"(substr10 aString)
Assert.equal "a" (substr(-1)1aString)
US>Asert.equal" "(substr1(-1)aString)
Assert.equal "la" (substr'(-3)aString)
Assert.equal "ozilla" (substr'1 aString)
Assert.equal "Mo" (substr(-20)2aString)
US>Asert.equal "(substr202 aString)
If start
or length
is not a negative number, you can write it a little more clearly.
substr::Int->Int->String->String
substr start length s =
Maybe.fromMaybe"(CodeUnits.slice start(start+length)s)
substr'::Int->String->String
substr' = CodeUnits.drop
It has nothing to do with the question, but it might be better to use substring
instead of substr
in JavaScript. https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/String/substr
© 2024 OneMinuteCode. All rights reserved.