Files
js-maker/demo/dom-exercises.rkt
T

84 lines
2.6 KiB
Racket

#lang racket/base
(require "../main.rkt")
(provide exercise01
exercise02
exercise03
exercise04
exercise05
all-dom-exercises
show-dom-exercises)
;; JavaScript DOM Exercises 01 Tutorial: https://youtu.be/EHF7xBUAmrQ
;; Exercise 01
;; Highlight all words over 8 characters long in the paragraph text.
(define exercise01
(js
(let* ([p (send document querySelector "p")])
(set! p.innerHTML
(regexp-replace* #px"\\b\\w{9,}\\b"
p.innerHTML
(λ (word)
(string-append "<span style=\"background: yellow\">"
word
"</span>")))))))
;; Exercise 02
;; Add a link back to the source of the text after the paragraph tag.
(define exercise02
(js
(let* ([p (send document querySelector "p")])
(send p insertAdjacentHTML
"afterend"
"<a href=\"https://forcemipsum.com/\">Source: ForceM Ipsum</a>"))))
;; Exercise 03
;; Split each new sentence on to a separate line in the paragraph text.
;; A sentence is assumed to be terminated with a period.
(define exercise03
(js
(let* ([p (send document querySelector "p")])
(set! p.innerHTML
(regexp-replace* #rx"\\.\\s*" p.textContent ".<br>")))))
;; Exercise 04
;; Count the number of words in the paragraph tag and display the count
;; after the heading. Words are separated by one singular whitespace.
(define exercise04
(js
(let* ([heading (send document querySelector "h1")]
[p (send document querySelector "p")]
[words (regexp-split #rx" " p.textContent)]
[count (length words)])
(send heading insertAdjacentHTML
"afterend"
(string-append "<p>" (number->string count) " words</p>")))))
;; Exercise 05
;; Replace question marks with thinking faces and exclamation marks with
;; astonished faces.
(define exercise05
(js
(let* ([p (send document querySelector "p")]
[step (regexp-replace* #rx"\\?" p.innerHTML "🤔")]
[out (regexp-replace* #rx"!" step "😲")])
(set! p.innerHTML out))))
(define all-dom-exercises
`((exercise01 . ,exercise01)
(exercise02 . ,exercise02)
(exercise03 . ,exercise03)
(exercise04 . ,exercise04)
(exercise05 . ,exercise05)))
(define (show-dom-exercises)
(for ([entry (in-list all-dom-exercises)])
(displayln (format "// ~a" (car entry)))
(displayln (cdr entry))
(newline)))
(module+ main
(show-dom-exercises))