diff --git a/main.rkt b/main.rkt index 85f8f20..04347bf 100644 --- a/main.rkt +++ b/main.rkt @@ -153,6 +153,11 @@ (hash? . -> . txexpr-attrs?) (hash-map hash list)) +(define+provide+safe (attrs-have-key? x key) + ((or/c txexpr-attrs? txexpr?) can-be-txexpr-attr-key? . -> . boolean?) + (define attrs (if (txexpr-attrs? x) x (get-attrs x))) + (hash-has-key? (attrs->hash attrs) (->txexpr-attr-key key))) + (define+provide+safe (attr-set tx key value) (txexpr? can-be-txexpr-attr-key? can-be-txexpr-attr-value? . -> . txexpr?) (define new-attrs diff --git a/scribblings/txexpr.scrbl b/scribblings/txexpr.scrbl index 9ef74f7..e98b93b 100644 --- a/scribblings/txexpr.scrbl +++ b/scribblings/txexpr.scrbl @@ -270,6 +270,19 @@ Convert @racket[_attrs] to an immutable hash, and back again. (hash->attrs '#hash((class . "red") (id . "top"))) ] +@defproc[ +(attrs-have-key? +[attrs (or/c txexpr-attrs? txexpr?)] +[key can-be-txexpr-attr-key?]) +boolean?] +Returns @racket[#t] if the @racket[_attrs] contain a value for the given @racket[_key], @racket[#f] otherwise. + +@examples[#:eval my-eval +(define tx '(div [[id "top"][class "red"]] "Hello" (p "World"))) +(attrs-have-key? tx 'id) +(attrs-have-key? tx 'grackle) +] + @defproc[ (attr-ref [tx txexpr?] diff --git a/tests.rkt b/tests.rkt index c4d7a51..b4bb2dc 100644 --- a/tests.rkt +++ b/tests.rkt @@ -88,6 +88,11 @@ (check-equal? (attr-ref '(p ((foo "bar"))) 'foo) "bar") (check-equal? (attr-set '(p ((foo "bar"))) 'foo "fraw") '(p ((foo "fraw")))) +(check-true (attrs-have-key? '(p ((color "red")(shape "circle"))) 'color)) +(check-true (attrs-have-key? '(p ((color "red")(shape "circle"))) "color")) +(check-false (attrs-have-key? '((color "red")(shape "circle")) 'nonexistent)) + + (check-equal? (merge-attrs 'foo "bar") '((foo "bar"))) (check-equal? (merge-attrs '(foo "bar")) '((foo "bar"))) (check-equal? (merge-attrs '((foo "bar"))) '((foo "bar")))