- Rethinking the JavaScript ternary operator1
- Break a forEach Loop with JavaScript2
- You Can Label a JavaScript
ifStatement | CSS-Tricks3 - Refactoring optional chaining into a large codebase: lessons learned – Lea Verou4
- [HTML5] 꼼꼼히 살펴보는 SCRIPT 엘리먼트 - 코드쓰는사람5
- Single Page Applications using Rust6
- Fast and maintainable patterns for fetching from a database – Sophie Alpert7
- Deep-copying in JavaScript using structuredClone8
- Holistic Review of TC39 “Dataflow” Proposals — Tab Completion9
Footnotes
-
삼항연산자(ternary)의 어두운면과 우려를 나타내는 글 ↩
-
forEach루프break하는 트릭. 참조하는 배열의 length값을 0으로. ↩ -
조건문에서
label을 지정해서 해당 블록으로break가 가능하다는걸 보여주는 내용. 실제 적용할만한 사례는 거의 없고 글쓴이는 while+switch문에서 break를 좀 더 효율적으로 사용한 예를 보여주고 있다. ↩ -
optional chaining 문법으로 리팩토링 하면서…변경 가능한 부분(삼항연산자, 배열, 기능탐지)과 주의사항(값 할당, 잘못된 위치에 표기), 조심할 부분(null/undefined, 연산 순서와 순위, return 항상 호출됨)으로 구분해서 정리한 글. 커밋을 보면 실제로 어떻게 작업했는지 확인도 가능하다. ↩
-
<script />태그와 속성값에 대한 정리 ↩ -
rust로 작성하고 wasm으로 컴파일해서 클라이언트 프로그램을 작성하는 방법을 자세하게 설명하고 있다. rust에 관심이 있거나 하다면 볼만한 글. ↩
-
종속성 구조를 파악해서 최적의 병렬화로 빠르게 데이터 가져오기 ↩
-
structuredClone()↩ -
pipe, flow 제안(초안)사항을 검토하는 관점에서 보는 시각 ↩
- Temporal documentation1
- Is It Time for the JavaScript Temporal API?2
- JS Dates Are About to Be Fixed | TimeTime
- Using Intl.RelativeTimeFormat for Localized Relative Timings
- Everything You Need to Know About Date in JavaScript | CSS-Tricks3
- 자바스크립트에서 타임존 다루기 (1) : NHN Cloud Meetup4
- 자바스크립트에서 타임존 다루기 (2) : NHN Cloud Meetup
Footnotes
-- new Date(문자열): 엔진이 보장하는 건 ISO 형식뿐
newDate :: Engine -> String -> Maybe Date
newDate _ s | isIso s = Just (parseIso s) -- "2022-04-09T12:00:00"
newDate Safari _ = Nothing -- "2022-04-09 12:00:00" → Invalid Date
newDate e s = implementationDefined e s
-- 형식을 명시해 읽는다: isAfter(new Date(), parse(DATE, 'yyyy-MM-dd HH:mm:ss', new Date()))
- An Intro to JavaScript Proxy | CSS-Tricks1
- Javascript Proxies : Real World Use Cases – Arbaz Siddiqui2
- JavaScript Proxy with Storage
- Getting Started with JavaScript Proxy Object3
- Evan You on Proxies - Advanced Components | Vue Mastery4
Reflect
- JavaScript: Why Reflect APIs?
- JavaScript Proxy. 근데 이제 Reflect를 곁들인 | TOAST UI :: Make Your Web Delicious!
- The global
Reflectobject, its use cases and things to watch out for | Stefan Judis Web Development - How JavaScript works: Proxy and Reflect | by Ukpaiugochi | SessionStack Blog
- Reflection at Reflect: The Reflect and Proxy APIs | Reflect
Footnotes
-- 속성 키는 문자열이나 Symbol — 그 밖의 값은 문자열로 바뀐다
key :: Value -> Either Symbol String
key (Sym s) = Left s
key v = Right (toString v) -- 숫자·배열·객체 모두
toString ["a"] == "a" -- obj[['a']] == obj.a
toString ["a", "b"] == "a,b"
- Promises From The Ground Up • Josh W. Comeau
- ⭐️🎀 JavaScript Visualized: Promises & Async/Await - DEV Community
- JavaScript Visualized - Promise Execution
- Running Promises In Parallel: A Visual Guide | JulesBlom.com
- await vs return vs return await - JakeArchibald.com1
- The gotcha of unhandled promise rejections - JakeArchibald.com
- 14 Linting Rules To Help You Write Asynchronous Code in JavaScript - Maxim Orlov2
- Async/Await without Try/Catch Block in JavaScript3
- Cancelable Async Flows4
- ECMAScript 2024 feature:
Promise.withResolvers()
Footnotes
-- Map 을 localStorage 에: JSON.stringify(map) 은 "{}" — 엔트리 배열로 왕복한다
save :: Map k v -> String
save = encode . Map.toList -- JSON.stringify([...map]) · localStorage 는 문자열만 저장 → 직렬화 필수
load :: Maybe String -> Map k v
load = maybe Map.empty (Map.fromList . decode) -- new Map(JSON.parse(data))
set k v = modify (Map.insert k v) >> persist -- 바꿀 때마다 통째로 다시 저장
-- 출처당 5MiB: 넘으면 setItem 이 QuotaExceededError
-- 전화번호: 숫자만 남기고 (길이, 02 접두) 로 그룹 자릿수를 고른다
groups :: String -> Maybe [Int]
groups ds = case (length ds, "02" `isPrefixOf` ds) of
(11, _) -> Just [3, 4, 4]
(10, True) -> Just [2, 4, 4]
(10, False) -> Just [3, 3, 4]
(9, True) -> Just [2, 3, 4]
_ -> Nothing -- 'Invalid phone number'
format :: String -> Maybe String
format raw = intercalate "-" . splitPlaces' ds <$> groups ds
where ds = filter isDigit raw
-- replace 는 매치된 곳만 바꾸고 나머지는 뒤에 남긴다 → sum groups == length ds 여야 한다
-- 거리 → 만km. toFixed(1): 반올림하고 0 까지 채운 문자열
formatToManKm :: Double -> String
formatToManKm d = showFFloat (Just 1) (d / 10000) "만km"
formatToManKm 104335 == "10.4만km"
formatToManKm 100000 == "10.0만km" -- 10만km 가 아니다
-- 목록에 든 특수 기호만 지운다 (영문·숫자·한글·공백은 남는다)
removeSpecialCharacters :: String -> String
removeSpecialCharacters = filter (`notElem` specials)
where specials = "!@#$%^&*()_+-=[]{};':\"\\|,.<>/?"
removeSpecialCharacters "Hello_World123! 안녕하세요?" == "HelloWorld123 안녕하세요" -- _ 도 목록에 있다
-- delete 는 configurable 한 자기 속성만 지운다
delete :: Mode -> Object -> Key -> Either Error Bool
delete _ o k | not (hasOwn o k) = Right True -- 없는 속성도 True
| configurable o k = Right True -- 지운다
delete Sloppy _ _ = Right False -- non-configurable
delete Strict _ _ = Left TypeError -- 모듈·클래스 안
-- 변수는 못 지운다: sloppy False · strict SyntaxError
delete Sloppy arr 1 == Right True -- [1, <empty>, 3] 구멍이 남는다 → 배열은 splice
-- 깊이 우선: 한 갈래를 끝까지 내려간 뒤 돌아온다
dfs :: Graph -> Node -> [Node]
dfs g start = go [start] []
where
go [] seen = reverse seen
go (n : st) seen
| n `elem` seen = go st seen
| otherwise = go (g ! n ++ st) (n : seen) -- 이웃을 앞에: 첫 이웃이 먼저 (JS 스택은 reverse 후 push)
-- 재귀로 쓰면 돌아올 자리를 콜 스택이 기억한다
graph = fromList [(0, [1, 2]), (1, [0, 3, 4]), (2, [0, 5]), (3, [1]), (4, [1]), (5, [2])]
dfs graph 0 == [0, 1, 3, 4, 2, 5]
-- 캔버스 프레임 · 서버가 준 음성 파일 → 둘 다 Blob → URL 로 바꿔 태그에 꽂는다
objectUrl :: Blob -> IO Url -- URL.createObjectURL(blob) → "blob:…"
show :: Blob -> IO ()
show b = objectUrl b >>= \u -> setSrc img u -- 음성이면 <audio>
-- axios: { responseType: 'blob' }
The
Generatorobject is returned by a generator function and it conforms to both the iterable protocol and the iterator protocol.
useGenerator— 핸들러를 async generator 로 받아 yield 마다 상태를 바꾼다- Iterator Helpers — async generator 페이지네이션을
take로 조기 종료 - Maybe Monad — generator 로 early return
- Async iterators and generators - JakeArchibald.com1
- How to consume a paginated API using JavaScript async generators
- Why would anyone need JavaScript generator functions?
Footnotes
-
Streaming 작업 시 비동기처리 방법을 알려주고 있는데…경험이 없어서 일단 메모. ↩
-- JS Number = IEEE 754 64비트 (Python·Java·C++ 의 double 과 같다)
0.1 + 0.2 /= 0.3 -- 0.30000000000000004
-- 0.1 은 이진법으로 0.0001100110011… 무한 반복 → 가장 가까운 값으로 잘려 저장된다
-- 피하는 길
viaInt = (1.1 * 10 + 0.1 * 10) / 10 -- 정수로 바꿔 계산
viaFixed = parseFloat (toFixed 1 (1.1 + 0.1)) -- 잘라서
close a b = abs (a - b) < epsilon * max (abs a) (abs b) -- 비교는 크기에 비례한 허용 오차
abs (1.1 + 0.1 - 1.2) == epsilon -- 그래서 `< epsilon` 만 쓰면 False
-- 정밀 계산: decimal.js · big.js · bignumber.js
-- 로컬 시간 기준 요일 (0 = 일, 6 = 토)
getDay :: Date -> Int
getDay (local 2024 11 25) == 3 -- 수요일. 월은 0 부터
getDay (parse "2024-12-25") == 2 -- UTC 보다 느린 시간대(미국 등)에서
-- 날짜만 쓴 문자열은 UTC 자정, 날짜+시각은 로컬로 읽는다
dayName d = ["일", "월", "화", "수", "목", "금", "토"] !! getDay d
-- 지금부터 목표 시각("18:30:00")까지 남은 시간
remaining :: Time -> Time -> Maybe (Int, Int, Int)
remaining now target
| diff < 0 = Nothing -- 이미 지났다
| otherwise = Just ( diff `div` 3600000 `mod` 24
, diff `div` 60000 `mod` 60
, diff `div` 1000 `mod` 60 )
where diff = target - now -- Date − Date: 숫자 문맥이라 둘 다 타임스탬프(ms)가 된다
-- target 은 오늘 날짜에 setHours h m s
remaining (today 16 14 30) (today 18 30 0) == Just (2, 15, 30)
-- 두 요소의 가로 스크롤을 비율로 맞춘다. 서로 리스너를 건다
sync :: Box -> Box -> Ignore -> (IO (), Ignore)
sync source target ignore
| ignore == Just source = (pure (), Nothing) -- 내가 일으킨 이벤트 하나를 건너뛴다
| scrollLeft target == next = (pure (), ignore) -- 값이 같으면 이벤트도 안 온다 — 표시하면 다음 사용자 스크롤을 삼킨다
| otherwise = (scrollLeft target := next, Just target)
where ratio = scrollLeft source / (scrollWidth source - clientWidth source)
next = round (ratio * (scrollWidth target - clientWidth target))
-- 동기 플래그로는 못 막는다: scroll 이벤트는 넣는 순간이 아니라 다음 렌더링에 온다
isSyncing := True >> scrollLeft target := next >> isSyncing := False -- 이벤트가 올 때 이미 False
-- 콜백 → Promise → async/await: 같은 세 단계를 쓰는 세 가지 방법
callback = fetchData (processData (displayData)) -- 안으로 중첩
chain = fetchData >>= processData >>= displayData -- then 으로 옆으로
main = do -- 위에서 아래로
d <- fetchData
p <- processData d
displayData p
-- then 은 모나드의 >>= 와 map 을 한 메서드로 한다
then :: Promise a -> (a -> b | Promise b) -> Promise b
then p f = case f x of
Promise q -> q -- 풀어서 잇는다 (flatMap)
v -> resolve v -- 감싼다 (map)
-- 그래서 Promise (Promise a) 는 만들어지지 않는다 — thenable 도 같은 식으로 푼다
-- 이벤트 루프 한 턴: 매크로는 하나, 마이크로는 빌 때까지 전부
turn :: Loop -> Loop
turn = render . drain . runOldest -- 렌더는 필요할 때만
drain :: Loop -> Loop
drain l = case micro l of
[] -> l
m : ms -> drain (run m l { micro = ms }) -- m 이 넣은 마이크로도 이 재귀가 받는다
-- 그래서 then·queueMicrotask 는 항상 setTimeout(0) 보다 먼저다
-- 마이크로가 계속 마이크로를 넣으면 drain 이 안 끝난다 — 렌더와 다음 매크로가 굶는다
-- setTimeout timeout · then (log "then" >> queueMicrotask nested) · log "sync"
order == ["sync", "then", "nested", "timeout"]
-- sync 스크립트 자체가 첫 매크로
-- then, nested 같은 drain
-- timeout 다음 turn 의 runOldest-- 커서 페이지네이션을 게으른 리스트로: 당겨질 때만 다음 페이지를 fetch 한다
pages :: Maybe Url -> [Item]
pages Nothing = []
pages (Just url) = items ++ pages next
where Page items next = fetch url -- 현재 페이지를 다 당긴 뒤에야 다음 페이지
-- 조기 종료는 take 가 맡는다: 10개가 2페이지에서 차면 3페이지는 평가되지 않는다
firstValid :: [Item]
firstValid = take 10 . filter isValid . pages $ Just "/api/items"
-- 요청 수를 세면 확인된다
-- JS: Iterator 는 네이티브(Node 22+), AsyncIterator 는 Stage 2 — core-js 폴리필, TS 선언은 직접
-- 제안이 개정 중이다 — 동시 next() 동작이 미정이라 폴리필과 다를 수 있다. 순차로 당기는 toArray 엔 영향 없음
-- location.href 에 넣으면 그 줄에서 멈추고 이동할 것 같다 — 암묵적 await 처럼. 아니다
setHref :: Url -> JS () -- Promise 가 아니다: 이동 요청만 등록하고 바로 돌아온다
setHref = enqueueNavigation
-- 실험: 실행됨 1·2 가 둘 다 찍히면 await 가 아니다 (CDP 로 확인)
-- await 였다면 첫 줄에서 멈춰 실행됨 1 도 안 찍히고 /a 로 가야 한다
experiment = do
setHref "/a"; log "실행됨 1"
setHref "/b"; log "실행됨 2"
-- 이동은 지금 코드가 끝난 뒤 시작되고, 새 이동이 앞의 것을 취소한다 (ERR_ABORTED)
arrived :: [Url] -> Url
arrived = last -- 덮어써서가 아니라 /a 가 시작됐다 끊겨서
-- 버려진 이동도 서버에는 갔다 (서버 기록 ["/a","/b"]) — 취소는 클라이언트에서만, 572
-- 서버 부수효과가 있는 URL(로그아웃 링크 같은)이면 "결국 /b 로 갔으니 /a 는 없던 일" 이 아니다
serverSaw :: [Url] -> [Url]
serverSaw = id- How to Modify Nodes in an Abstract Syntax Tree | CSS-Tricks1
- AST for JavaScript developers. TL;DR This article is my talk for… | by Bohdan Liashenko | ITNEXT2
- GitHub - NV/CSSOM: Unmaintained! ⚠️ CSS Object Model implemented in pure JavaScript. Also, a CSS parser.3
- GitHub - csstree/csstree: A tool set for CSS including fast detailed parser, walker, generator and lexer based on W3C specs and browser implementations
Footnotes
-- 플러그인 시스템: 코어는 등록받은 플러그인을 정해진 지점에서 부를 뿐
type Plugin = Core -> Core
register :: Plugin -> [Plugin] -> [Plugin]
register = (:)
run :: [Plugin] -> Core -> Core
run plugins core = foldr ($) core plugins -- 코어를 고치지 않고 기능을 더한다
-- thisArg = 콜백의 this. 비교할 값을 this 로 받는 함수 하나를 재사용
filterWith :: (b -> a -> Bool) -> b -> [a] -> [a]
filterWith pred this = filter (pred this) -- arr.filter(callback, thisArg)
isId :: Int -> Item -> Bool
isId this item = itemId item == this -- function isId(item) { return item.id === this }
filterWith isId 3 items
-- 화살표 함수는 자기 this 가 없어 thisArg 무시 · 화살표보다 느릴 수 있다