From 78ac03a8efc9d5c4b9e557934088f400dd08dd2f Mon Sep 17 00:00:00 2001 From: Gareth Daniel Smith Date: Sat, 4 Aug 2018 23:02:02 +0100 Subject: [PATCH] Add a new toArray function, to make it easy to deal with each matched element individually. Also add some tests/docs for the length function. --- src/Cheerio.purs | 14 +++++++++++++- test/Test/Cheerio.purs | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Cheerio.purs b/src/Cheerio.purs index 6bc56e3..570d8f5 100644 --- a/src/Cheerio.purs +++ b/src/Cheerio.purs @@ -13,9 +13,13 @@ module Cheerio ( parent, prev, siblings, - text + text, + toArray ) where +import Prelude + +import Data.Array ((..)) import Data.Function.Uncurried (Fn2, Fn3, Fn4, runFn2, runFn3, runFn4) import Data.Maybe (Maybe(..)) @@ -67,4 +71,12 @@ html = runFn3 htmlImpl Nothing Just foreign import text :: Cheerio -> String -- Miscellaneous + +-- | Get how many elements there are in the given Cheerio foreign import length :: Cheerio -> Int + +-- | Seperate each element out into its own Cheerio +toArray :: Cheerio -> Array Cheerio +toArray c + | length c == 0 = [] + | otherwise = map (\i -> eq i c) (0 .. (length c - 1)) diff --git a/test/Test/Cheerio.purs b/test/Test/Cheerio.purs index fdd6eb3..437bd2d 100644 --- a/test/Test/Cheerio.purs +++ b/test/Test/Cheerio.purs @@ -24,6 +24,7 @@ import Cheerio , prev , siblings , text + , toArray ) import Cheerio.Static (loadRoot) @@ -138,6 +139,25 @@ suites = do "" (emptyCheerio # text) + suite "Miscellaneous" do + test "length" do + Assert.equal + 0 + (emptyCheerio # length) + + Assert.equal + 3 + (loadRoot htmlEx # find "li" # length) + + test "toArray" do + Assert.equal + [] + (emptyCheerio # toArray # map (attr "class")) + + Assert.equal + (map Just ["apple", "orange", "pear"]) + (loadRoot htmlEx # find "li" # toArray # map (attr "class")) + suite "More" do test "Long chain" do Assert.equal