Saturday, August 23, 2025

"You Don't Know JS: Async & Performance" Kyle Simpson

 


Book notes:

“setTimeout(…) timers may not fire with perfect temporal accuracy. You’re guaranteed (roughly speaking) that your callback won’t fire before the time interval you specify, but it can happen at or after that time, depending on the state of the event queue.”

“Parallel Threading. It’s very common to conflate the terms “async” and “parallel,” but they are actually quite different. Remember, async is about the gap between now and later. But parallel is about things being able to occur simultaneously.”

“The most common tools for parallel computing are processes and threads. Processes and threads execute independently and may execute simultaneously: on separate processors, or even separate com-puters, but multiple threads can share the memory of a single process.”

“threaded programming is very tricky, because if you don’t take special steps to prevent this kind of interruption/interleaving from happening, you can get very surprising, nondeterministic behavior that frequently leads to headaches.”

“JavaScript never shares data across threads, which means that level of nondeterminism isn’t a concern.”

“setTimeout(…0) is not technically inserting an item directly onto the event loop queue. The timer will insert the event at its next opportunity. For example, two subsequent setTime out (… 0) calls would not be strictly guaranteed to be processed in call order, so it is possible to see various conditions like timer drift where the ordering of such events isn’t predictable. In Nodejs, a similar approach is process.next Tick(…). Despite how convenient (and usually more performant) it would be, there’s not a single direct way (at least yet) across all environments to ensure async event ordering.”

“A JavaScript program is (practically) always broken up into two or more chunks, where the first chunk runs now and the next chunk runs later, in response to an event. Even though the program is executed chunk-by-chunk, all of them share the same access to the program scope and state, so each modification to state is made on top of the previous state. Whenever there are events to run, the event loop runs until the queue is empty. Each iteration of the event loop is a tick. User inter-action, 10, and timers enqueue events on the event queue. At any given moment, only one event can be processed from the queue at a time. While an event is executing, it can directly or indirectly cause one or more subsequent events. Concurrency is when two or more chains of events interleave over time, such that from a high-level perspective, they appear to be running simultaneously (even though at any given moment only one event is being processed). It’s often necessary to do some form of interaction coordination between these concurrent “processes” (as distinct from operating system processes), for instance to ensure ordering or to prevent race conditions. These “processes” can also cooperate by breaking themselves into smaller chunks and to allow other “process” interleaving.”

“it was decided that the way to recognize a Promise (or something that behaves like a Promise would be to define something called a thenable as any object or function which has a then (…) method on it. It is assumed that any such value is a Promise-conforming thenable.”

“you should never rely on anything about the ordering/scheduling of callbacks across Promises. In fact, a good practice is not to code in such a way where the ordering of multiple callbacks matters at all. Avoid that if you can.”

“fundamental principle that Promises are immutable once resolved.”

“If you pass an immediate, non-Promise, non-thenable value to Promise. resolve(…), you get a promise that’s fulfilled with that value. In this case, promises p1 and p2 will behave identically”

“The most natural form of error handling for most developers is the synchronous try…catch construct. Unfortunately, it’s synchronous-only, so it fails to help in async code patterns”

“Promise.all([ … ]) expects a single argument, an array, consisting generally of Promise instances. The promise returned from the Promise.all([… ]) call will receive a fulfillment message (msgs in this snippet) that is an array of all the fulfillment messages from the passed in promises, in the same order as specified (regardless of fulfillment order).”

“Technically, the array of values passed into Promise.all(l … ]) can include Promises, thenables, or even immediate values. Each value in the list is essentially passed through Promise. resolve(…) to make sure it’s a genuine Promise to be waited on, so an immediate value will just be normalized into a Promise for that value. If the array is empty, the main Promise is immediately fulfilled.”

“A race requires at least one “runner,” so if you pass an empty array, instead of immediately resolving, the main race([…]) Promise will never resolve.”

“none ([ … ]) - This pattern is like all ([ … ]), but fulfillments and rejections are transposed. All Promises need to be rejected-rejections become the fulfillment values and vice versa. any ([ … ]) - This pattern is like all([ … ]), but it ignores any rejections, so only one needs to fulfill instead of all of them. first([ … ]) - This pattern is like a race with any ([ … ]), which means that it ignores any rejections and fulfills as soon as the first Promise fulfills. last([ … ]) - This pattern is like first([ … ]), but only the latest fulfillment wins.”

“The revealing constructor Promise(.) must be used with new, and must be provided a function callback, which is synchronously/ immediately called. This function is passed two function callbacks that act as resolution capabilities for the promise. We commonly label these resolve(…) and reject… )”

“reject(…) simply rejects the promise, but resolve(…) can either fulfill the promise or reject it, depending on what it’s passed. If resolve(…) is passed an immediate, non-Promise, non-thenable value, then the promise is fulfilled with that value. But if resolve(…) is passed a genuine Promise or thenable value, that value is unwrapped recursively, and whatever its final resolu-tion/state is will be adopted by the promise.”

“A shortcut for creating an already-rejected Promise is Promise. reject(… )”

“Promise.resolve(…) is usually used to create an already-fulfilled Promise”

“And remember, Promise. resolve(…) doesn’t do anything if what you pass is already a genuine Promise; it just returns the value directly.”

“Each Promise instance (not the Promise API namespace) has then (…) and catch(…) methods, which allow registering of fulfillment and rejection handlers for the Promise. Once the Promise is resolved, one or the other of these handlers will be called, but not both, and it will always be called asynchronously”

“then(…) and catch(…) also create and return a new promise, which can be used to express Promise chain flow control.”

“Promise.wrap(…) does not produce a Promise. It produces a function that will produce Promises.”

“The act of wrapping a callback-expecting function to be a Promise-aware function is sometimes referred to as “lifting” or “promisify-ing”.”

“As of ES6, the way to retrieve an iterator from an iterable is that the iterable must have a function on it, with the name being the special ES6 symbol value Symbol. iterator. When this function is called, it returns an iterator. Though not required, generally each call should return a fresh new iterator.”

“The purpose of yield-delegation is mostly code organization, and in that way is symmetrical with normal function calling.”

“The key benefit of generators related to async flow control is that the code inside a generator expresses a sequence of steps for the task in a naturally sync/sequential fashion. The trick is that we essentially hide potential asynchrony behind the yield keyword-moving the asynchrony to the code where the generator’s iterator is controlled. In other words, generators preserve a sequential, synchronous, blocking code pattern for async code, which lets our brains reason about the code much more naturally, addressing one of the two key drawbacks of callback-based async.”

“an environment like your browser can easily provide multiple instances of the JavaScript engine, each on its own thread, and let you run a different program in each thread. Each of those separate threaded pieces of your program is called a (Web) Worker. This type of parallelism is called task parallelism, as the emphasis is on splitting up chunks of your program to run in parallel.”

“To kill a Worker immediately from the program that created it, call terminate() on the Worker object”

“Inside the Worker, you do not have access to any of the main program’s resources. That means you cannot access any of its global variables, nor can you access the page’s DOM or other resources. Remember: it’s a totally separate thread. You can, however, perform network operations (Ajax, WebSockets) and set timers. Also, the Worker has access to its own copy of several important global variables/features, including navigator, loca tion, JSON, and applicationCache.”

“What are some common uses for Web Workers? • Processing intensive math calculations • Sorting large data sets. • Data operations (compression, audio analysis, image pixel manipulations, etc.) • High-traffic network communications”

“typed arrays like UintArray (see the ES6 & Beyond title of this series) are Transferables.”

“Shared Workers survive the termination of a port connection if other port connections are still alive, whereas dedicated Workers are terminated whenever the connection to their initiating program is terminated.”

“Single instruction, multiple data (SIMD) is a form of data parallel-ism, as contrasted to task parallelism with Web Workers, because the emphasis is not really on program logic chunks being parallel-ized, but rather multiple bits of data being processed in parallel.”

“asm.js is a label for a highly optimizable subset of the JavaScript lan-guage. By carefully avoiding certain mechanisms and patterns that are hard to optimize (garbage collection, coercion, etc.), asm.js-styled code can be recognized by the JS engine and given special attention with aggressive low-level optimizations.”

“Luckily, smart folks like John-David Dalton and Mathias Bynens do understand these concepts, and wrote a statistically sound benchmarking tool called Benchmark.js. So I can end the suspense by simply saying: “just use that tool.””

“What this boils down to is that testing not real code gives you not real results. If possible and practical, you should test actual real, nontrivial snippets of your code, and under as best of real conditions as you can actually hope to. Only then will the results you get have a chance to approximate reality.”

“jsPerf. It uses the Benchmark.js library we talked about earlier to run statistically accurate and reliable tests, and makes the test on an openly available URL that you can pass around to others.”

“jsPerf.com is a fantastic website for crowdsourcing performance benchmark test”

Wednesday, August 13, 2025

"Не змушуйте мене думати" Стів Круг

 

тренажер для швидкого читання (промо)


Нотатки з книги:

“дизайн користувацького досвіду (User Experience Design, скорочено UXD або просто UX) — термін, що позначає будь-яку діяльність або професію, яка сприяє поліпшенню досвіду користувачів.”

“Usability (англ.) - використовність, зручність використання.”

“використовність — це про людей, про те, як вони розуміють якусь річ і як послуговуються нею, а не про технології. І якщо технології зчаста змінюються швидко, то людство — повільно”

“Що коротша книжка, то більше шансів, що її прочитають. [Ось чудовий принцип використовності: коли щось потребує або може потребувати великих витрат часу, цим навряд чи будуть користуватися.]”

“«Не змушуйте мене думати!» Скільки працюю, завжди кажу людям, що це перший закон викорис-товності. Головний принцип, який ставить крапку у рішенні, функціональний дизайн чи ні. Якщо ваша памʼять здатна вмістити лише одне правило використовності, то нехай у ній закарбується саме це.”

“кожне запитання - це додаткове навантаження на мозок. Зайві роздуми відвертають нашу увагу від завдання. Спершу цього можна й не помітити, але якщо будемо постійно гадати, що ж натиснути, то зауважимо, що зосередитися нам става-тиме все важче.”

“щоб вебсторінка була ефективною, вона повинна справляти враження відразу. Цього можна досягти, якщо її зміст і вигляд — самоочевидні або принаймні зрозумілі.”

“ФАКТ #1: Ми не читаємо сторінки. Ми проглядаємо їх.”

“ФАКТ #2: Ми не шукаємо найкращого варіанту. Ми шукаємо прийнятний.”

“Я роками спостерігав таку поведінку, але поки не прочитав книжку Гері Кляйна «Джерела влади: Як люди ухвалюють рішення», не надавав цьому великої ваги. Кляйн багато літ вивчав, як люди різних професій, зокрема пожежники, пілоти, шахісти та оператори атомних електростанцій, ухвалюють важливі рішення за складних обставин, коли часу обмаль, цілі нечіткі, інформації бракує, а ситуація мінлива.”

“ФАКТ #3: Ми не знаємо, як треба. Ми пробуємо, поки не вийде.”

“Моя порада: впроваджуйте щось нове лише коли впевнені, що ваш задум кращий; якщо вагаєтесь - дотримуйтесь усталених норм.”

“Систематичність — це справді те, до чого варто прагнути, коли створюєш вебсайт або мобільний застосунок. Якщо навігацію, наприклад, завжди розміщують в одному і тому ж місці, то ми про неї й не думаємо, не гайнуємо часу, щоб її знайти. Але може трапитися так, що для того, аби вебсайт був зрозумілішим, доведеться трішки відійти від звичної схеми.”

“закарбуйте у памʼяті таке правило: ЛЕГКІСТЬ У СПРИЙНЯТТІ ВАЖЛИВІША ЗА СИСТЕМАТИЧНІСТЬ”

“вебсторінок. Дон Норман у новому виданні своєї книжки про використовність «Дизайн звичних речей» дуже гарно пояснює, що насправді ми у всьому (наприклад, у дверних ручках) шукаємо такі підказки (щоб зрозуміти, двері відчиняються на себе чи від себе). Прочитайте цю книжку і ви вже ніколи не дивитиметеся на двері так, як раніше.”

“Коли редагуєте вебсторінку, памʼятайте, будь-що може створювати візуальний шум (обирайте підхід «від зворотного») і заберіть елементи, що не мають великого значення. Користувачі, які проглядають вебсайт поспіхом, на все увагу не звертатимуть, тож неважливих компонентів слід одразу позбутися.”

“Якщо справді хочете дізнатися, як зробити текст зручним для швидкого аналізу (або якщо загалом цікавитеся усім, що повʼязане з написанням текстів в інтернеті), то не йдіть, а біжіть по свій телефон чи до компʼютера, і мерщій замовте книжку Дженні Редиш «Відпустіть слова».”

“Поки кожен рух простий та очевидний, неважливо скільки разів треба клацати. ДРУГИЙ ЗАКОН КРУГА”

“На перший погляд, «кількість натискань, потрібних, щоб кудись перейти» здається суттєвим показником. Та з часом я зрозумів, що насправді важливо не те, скільки разів треба клацати (хоча якась міра має бути), а радше наскільки складним є кожен рух — як довго треба думати, перед тим як щось зробити, і чи не викликає сумнівів будь-який крок.”

“У формах користувачів постійно простять зробити складний вибір чи відповісти на якісь мудруваті запитання. Керолайн Джерретт у своїй книжці «Форми, що працюють: створення вебформ для використовності» присвятила цій проблемі цілий розділ («Як спростити запитання»).”

“Позбудьтесь половини слів на кожній сторінці, а потім викиньте ще половину з того, що залишилося. ТРЕТІЙ ЗАКОН КРУГА”

“Позбудьтеся зайвих слів. Ефективне письмо лаконічне. Речення не повинно містити зайвих слів, абзац — зайвих речень, так само як на малюнку не має бути зайвих штрихів, а у пристрої — зайвих деталей”

“Жодних інструкцій. Інше велике джерело непотрібних слів — інструкції. Головне, що треба знати про інструкції, то це те, що їх ніхто не читає”

“Правило «навігація повинна бути всюди» має один виняток: форми. На сторінках, які містять форми для заповнення, постійна навігація іноді може зайвий раз відвертати увагу користувачів.”

“Назва сторінки повинна відповідати покликанню. Кожен сайт укладає зі своїми відвідувачами суспільний договір, який не підлягає розголошенню: Назва сторінки відповідає словам, на які я натиснув, щоб на неї потрапити.”

“Як на мене, вкладки — це чудовий засіб навігації, яким слід користуватися частіше. Ось чому вони мені подобаються: 1) Вкладки самоочевидні… 2) Їх складно не помітити., 3) Мають естетичне значення.”

“Якщо у перші кілька секунд не вдається вловити ідею сайту, трактувати елементи сторінки буде важче. Тож є більша ймовірність, що я зрозумію щось неправильно і в результаті розчаруюся.”

“Вітальне слово. Вітальне слово - це короткий опис сайту у вигляді примітного блока, який розміщують переважно у верхньому лівому куті головної сторінки або посередині, тому це перше, що впадає в око.”

“Слоган — це влучна фраза, яка описує компанію, передає суть і переваги діяльності.”

“Вдалі слогани містять достатню кількість слів. Шести-восьми слів цілком вистачить, щоб передати суть і щоб фраза легко сприймалася.”

“Вдалі слогани — вказують на відмінність і очевидні переваги.”

“нескінченні обговорення я зазвичай називаю «релігійними суперечками», тому що вони дуже нагадують більшість дискусій про релігію та політику. Усі палко відстоюють власну думку щодо речей, які насправді ніяк неможливо довести - нібито для того, щоб вибрати найкраще рішення стосовно чогось важливого (як-от досягнення вічного миру, ефективності управління чи просто розроблення вебсторінок). А ще, як і в більшості релігійних суперечок, котрась зі сторін рідко змінює свої погляди в результаті.”

“не існує ніякого середньостатистичного користувача… КОЖЕН КОРИСТУВАЧ ОСОБЛИВИЙ, І КОЖЕН СПОСІБ КОРИСТУВАННЯ ІНТЕРНЕТОМ ТЕЖ ВИНЯТКОВИЙ”

“Єдиний спосіб зʼясувати, чи вебсайт справді працює — поспостерігати за тим, як інші люди ним користуються.”

“те, що здається простим для вас, не обовʼязково таке ж очевидне і для інших.”

“Краще протестувати одного користувача, ніж не тестувати жодного.”

“Дистанційне тестування без модерації. Такі сервіси, як UserTesting.com, мають людей, що можуть пройти для вас тестування на відео.”

“Більшість проблем із забезпеченням зручності у користуванні мобільними пристроями зводиться до того, щоб знайти правильні компроміси.”

“Ознаки (affordances) — це візуальні підказки в дизайні обʼєкта, що допомагають зрозуміти, як його можна використовувати… Для того, щоб ознаки працювали, вони мають бути помітними,”

“Захват — це новий чорний. Що воно взагалі таке - «захват»? Захват дещо складно пояснити; це щось, що «можна зрозуміти, лише коли сам проймешся цим почуттям». Мабуть, замість шукати дефініцію, легше буде назвати слова, які люди вживають, коли говорять про продукти, що викликають у них захват: цікавий, незвичайний, приголомшливий, захопливий, оригінальний і навіть магічний. Застосунки, що здатні викликати захват, зазвичай виникають внаслідок синтезу двох ідей: того, що люди дуже хочуть могти робити, але вважають це неможливим, і того, як можна це здійснити, використовуючи новітні технології.”

“За моїми стандартами, застосунок, що викликає захват «має функці, за які вас кілька сотень років тому спалили б на вогнищі».”

“Інколи легкість у запамʼятовуванні є важливим чинником, який впливає на те, чи будуть люди повсякчас послуговуватися програ-мою. Зазвичай, коли ви купуєте застосунок, то готові присвятити певний час на те, щоб зрозуміти, як ним користуватися. Але коли наступного разу доводиться наново у всьому розбиратися, ви навряд чи будете від цього в захваті. Якщо застосунок вас не дуже вразив, ви полишите його - так роблять із багатьма.”

“Завжди вважав, що корисно уявляти собі, ніби у користувача, який заходить на вебсайт, завжди є певний запас лояльності. Із кожною проблемою, яка може йому трапитися на сайті, рівень лояльності знижується.”

“Більшість користувачів дуже скептично ставляться до запитів із проханням надати особисту інформацію і дратуються, коли сайт вимагає більше ніж потрібно для виконання поточного завдання.”

“сайтах. Свої спостереження автори описали в статті «Керівні принципи для доступних і зручних вебсай-тів: спостереження за користувачами, які працюють із екранними зчитувачами»”

“«Guidelines for Accessible and Usable Web Sites: Observing Users Who Work with Sereen Readers». Опубліковано в АСМ Magazine, Interactions (листопад-грудень, 2003). З дозволу АСМ, Джинні зробила її доступною для користування на https://redish.net/wp-content/uploads/Theorfanos_Redish_InteractionsPaperAuthorsVer.pdf”

“A Web for Everyone: Designing Accessible User Experiences by Sarah Horton and Whitney Quesenbery”

“Web Accessibility: Web Standards and Regulatory Compliance”

“It’s Our Research: Getting Stakeholder Buy-In for User Experience Research Projects”

“Книжка Лії Б’юлі The User Experience Team of One: A Research and Design Survival Guide… написана спеціально для тих, хто «єдиний у компанії практикує (чи хоче практикувати) дизайн, орієнтований на користувача»”

“пошукайте статтю «Don’t Put Labels Inside Text Boxes (Unless You’re Luke W)» («Не розміщуйте текстові підказки усередині полів”

#1 Додаток для Швидкочитання (промо) 

Tuesday, August 12, 2025

"Сліпа лють" Наталі Гейнс

 

основи швидкочитання (промо)

Нотатки з книги:

“Вона здатна спіймати що завгодно. А що може спіймати її? Ніщо. Тішилася власною силою.”

“це Метіда давала поради, коли Зевс боровся з титанами. Це Метіда допомагала перемогти Кроноса, його батька. Метіда, така хитра й розумна, завжди виношувала який-небудь план.”

“Сфено розуміла: це любов. І вона її відчувала, хоча того й не бажала.”

“Посейдон ніколи не відступиться. Як море здобуває всі свої перемоги? Виснаженням.”

“Не можна довести того, у що ти віриш, — сказала. — Ти просто віриш, та й по всьому.”

“— Байдуже, що вони про мене думають. — То нащо берешся їх захищати? — Бо можу.”

“Перший млинець нанівець.”

“— Використовуючи всього лише шолом-невидимку Аїда та мої крилаті сандалі, — додав Гермес. — І вигнутий меч від самого Зевса. І поради богині мудрості. — Схоже, для початку годиться, — сказав Персей.”

“Люди називають вас потворами тому, що вони вас не розуміють.”

“Тепер він наближається до горгони, готовий убити істоту, яка не зробила йому нічого поганого, аби здобути трофей для чоловіка, якого він зневажає. Чоловіки, здається, часто вбивають заради трофеїв. Тварин, звісно. Не дітей богів. Цих не часто. І не за допомогою інших, могутніших богів.”

“Він убачав у Медузі чудовисько, і він бачить Сфено й Евріалу такими самими. Якби він мав змогу їх уби-ти, він убив би. Усе, що він чує, — це небезпека від істоти, яка бажає йому зла. Він не чує горя чи втрати. Він запевняє, що піклується про сімʼю (пізніше я про це дізнаюся). От цікаво, що б відчула його мати, якби побачила обезголовлене тіло, що лежить перед нею на піску, де кілька хвилин тому вона залишила поснулого сина. Щоб ви розуміли, навіть через цю дію уяви я більше людина, аніж він.”

Thursday, August 7, 2025

"Світанок авторитаризму. Як ліві озброїли інституції США проти опонентів" Бен Шапіро

 



Кращі нотатки з книги:

“У людині є щось таке, що любить диктатора.”

“Американська політика загалом ділиться на три основні групи: консерватори, ліві та ліберали.”

“в лібералів залишається вибір. Вони можуть або сформувати коаліцію з лівими, з якими погоджуються щодо більшості політичних цілей, але мають розбіжності з фундаментальних принципів свободи, або ж сформувати коаліцію з кон-серваторами, з якими розходяться в поглядах на політичні цілі, але погоджуються з фундаментальних принципів свободи. Поки що цей вибір ще не зроблено.”

“Експресивний індивідуалізм — це основоположна ідея про те, що метою життя та держави має бути забезпечення людям можливості досліджувати своє сприйняття хорошого життя і виражати його на власний розсуд”

“Ставлення до науки як до політики підриває саму науку, а ставлення до політики як до науки коштує життів.”

“коли вченим дають змогу говорити за межами своєї галузі знань — займатися політичними справами, претендуючи на наукову чесність, — виникає сіра зона, у якій переплітаються політика й наука.”

“Це небезпечна річ. Небезпечно, що вартові нашої демократії — медіа — є не вартовими, а політичними активістами, відданими своїй пропаганді. Ще небезпечнішим є те, що тепер вони постійно працюють над тим, щоб заглушити голоси тих, з ким вони не згодні, і використовують міць своїх платформ, щоб знищувати власних супротивників на всіх рівнях. Квітучий ринок ідей потребує елементарної поваги до самого ринку. Але наші ідеологізовані авторитарні ліві медіа прагнуть зруйнувати цей ринок на користь монополії.”

“чому соціальні мережі перетворилися на таке палюче багаття внутрішньої ненависті?”

“Вони не можуть скасувати нас, якщо ми ім не дозволимо. Це має стати нашим бойовим кличем. Бо якщо ми, ліберали, центристи, консерватори, скажемо це разом, то авторитарні ліві програють.”

Monday, July 28, 2025

"Test-Driven Development with React and TypeScript: Building Maintainable React Applications" Juntao Qiu

 

Speed reading exercises (promo)

Book notes:

“TDD is a software development methodology in which tests are written to drive the development of an application. It was developed/rediscovered by Kent Beck in the late 1990s as part of Extreme Programming’ and was well discussed in his famous book Test-Driven Development: By Example.”

“Red-Green-Refactor is the core cycle of Test-Driven Development (TDD) methodology. The cycle involves the following steps: 1. Red: Write a failing test that describes the desired behavior of a specific feature or functionality. The test should not pass yet as the functionality has not yet been implemented. 2. Green: Write the minimum amount of production code necessary to make the failing test pass. The focus should be solely on passing the test, without worrying about code quality or design. 3. Refactor: Improve the design of the production code without changing its behavior, ensuring that all tests continue to pass. This step includes optimizing the code, removing duplication, and enhancing its overall quality.”

“When applying TDD, you need to keep in mind a simple principle from Extreme Programming: YAGNI, or You Aren’t Gonna Need It. YAGNI can be very useful for protecting developers from wasting their valuable time.”

“Domain-Specific Language (DSL) is used to write tests in natural language that can be easily understood by nontechnical people and can be interpreted by code and executed behind the scenes.”

“In his book Refactoring: Improving the Design of Existing Code, Martin Fowler listed 68 refactorings. I would recommend this book as almost a mandatory prerequisite for anyone who values clean code and high-quality code.”

“Jest is a testing framework from Facebook that allows developers to write reliable and fast-running tests in a more readable syntax. It can watch changes in test/ source files and rerun the necessary tests automatically.”

“In Jest, the describe function is used to group related tests together and create a logical structure within your test suite. It provides a way to organize and categorize tests based on a specific functionality, component, or feature.”

“The it function takes two arguments: a description string and a callback function. The description string describes what behavior or outcome you are testing. The callback function contains the actual test assertions or expectations.”

“To reduce duplication, we can utilize the beforeEach function provided by Jest to define reusable object instances. This function is automatically invoked before Jest runs each test case.”

“Jest provides an afterEach function that can be used to perform any necessary cleanup work after each test case has been run”

“toEqual and toBe may be the most common matchers you will find and use in almost every test case. As the name implies, they are used to assert whether values are equal to each other (the actual value and the expected value).”

“Jest also provides matchers for Array and Object.”

“that there is a difference between toContain and toContainEqual. Basically, toContain checks if the item is in the list by strictly comparing elements using ===. On the other hand, toContainEqual just checks the value (not the memory address).”

“we can make use of a technique called mocking where we simply simulate the function call rather than actually invoking it.”

“Jest provides a variety of ways to do this mock. The simplest one is function jest. fn for setting up a spy for a function”

“It is generally considered a best practice to keep files as small and focused as possible and to split them into separate files if they become too large.”

“A test can also be described in 3A format; the 3A (Arrange-Act-Assert) structure consists of three essential components of a test: 1. Arrange: The initial context or setup for the test 2. Act: The action or behavior being tested 3. Assert: The expected outcome or result of the test”

“It’s important to differentiate between end-to-end tests and unit tests. End-to-end tests simulate a user’s interaction with the entire application, while unit tests isolate and test individual functions or components of the application. Although end-to-end tests are great for testing the overall functionality and flow of the application, they can be slow and cumbersome to run. Unit tests, on the other hand, are faster, more focused, and can catch bugs before they make it into the codebase.”

“In React Router, the MemoryRouter is a specialized router component that allows you to manage routing within the memory of your application, rather than relying on the browser’s URL history. The MemoryRouter provides a router implementation that stores the current location and history in memory, making it useful for scenarios where you don’t need to update the browser’s URL or navigate between pages in a traditional sense.”

“The Publish-Subscribe (Pub-Sub) pattern is a messaging pattern commonly used in software architectures to facilitate communication between different components or modules. It provides a means for decoupling the sender (publisher) and receiver (subscriber) of messages, enabling them to interact without direct knowledge of each other.”

“The main principle of using Redux is the separation of concerns between the UI components and the application state.”

“In Redux, there are three principles that form its foundation: • All state is stored in a single global data source. • State is immutable or read-only. • Changes are made using pure functions.”

“The formula view = f(state) represents the relationship between the state and the view in a software application.”

“TypeScript is a typed superset of JavaScript that adds optional static typing and other features to the language. It allows developers to catch errors and bugs at compile time instead of runtime, making their code more robust and maintainable. TypeScript also provides advanced features like classes, interfaces, and modules that make it easier to write large-scale applications.”

fast reading practice (promo)

"Фундація" Айзек Азімов

  Додаток для Швидкочитання (промо) Нотатки з книги: “Цей ліфт був нового типу й рухався за допомогою гравітаційного відштовхування.” “ПСИХ...