├── README.md ├── package.json └── snippets ├── css-aspect-ratio-21-03-2022.css ├── css-clamp-function-14-03-2022.css ├── css-combining-filter-functions-11-03-2022.css ├── css-filter-blur-04-03-2022.css ├── css-filter-brightness-03-03-2022.css ├── css-filter-constrast-07-03-2022.css ├── css-filter-grayscale-08-03-2022.css ├── css-min-max-function-13-03-2022.css ├── css-trans-flag-31-03-2022.css ├── css-transform-origin-property-22-03-2022.css ├── css-transform-rotate-21-02-2022.css ├── css-transform-skew-23-02-2022.css ├── css-transform-translate-19-02-2022.css ├── html-generate-markup-with-emmet-28-02-2022.html ├── html-lorem-emmet-02-03-2022.html ├── html-template-emmet-01-03-2022.html ├── js-HTMLElement-innerText-09-03-2022.js ├── js-array-destructuring-30-03-2022.js ├── js-arrow-functions-21-04-2022.js ├── js-babel-16-06-2022.html ├── js-catch-finally-31-05-2022.js ├── js-constructors-05-05-2022.js ├── js-convert-string-to-number-16-03-2022.js ├── js-create-append-dom-node-14-06-2022.html ├── js-destructuring-objects-01-04-2022.js ├── js-do-while-vs-while-loop-10-03-2022.js ├── js-doc-calculate-tip-16-05-2022.js ├── js-empty-array-15-04-2022.js ├── js-equality-operators-17-03-2022.js ├── js-falsy-values-18-03-2022.js ├── js-getComputedStyle-29-04-2022.html ├── js-logical-and-assignment-19-04-2022.js ├── js-logical-or-assignment-20-04-2022.js ├── js-map-object-13-05-2022.js ├── js-math-floor-26-04-2022.js ├── js-math-max-min-08-04-2022.js ├── js-merge-arrays-06-04-2022.js ├── js-nullish-coalescing-operator-22-04-2022.js ├── js-object-entries-29-03-2022.js ├── js-object-values-26-03-2022.js ├── js-object.keys-method-25-03-2022.js ├── js-oop-setter-getter-06-05-2022.js ├── js-promise-all-28-05-2022.js ├── js-promise-async-await-syntactic-sugar-24-05-2022.js ├── js-promise-async-await-then-03-05-2022.js ├── js-promise-introduction-20-05-2022.js ├── js-promise-reject-30-05-2022.js ├── js-promise-setTimeout-11-04-2022.js ├── js-promise-then-chaining-23-05-2022.js ├── js-recursive-factorial-14-04-2022.js ├── js-remove-duplicates-array-05-04-2022.js ├── js-rest-parameters-07-10-2022.js ├── js-reverse-string-28-03-2022.js ├── js-set-07-04-2022.js ├── js-sorting-arrays-23-03-2022.js ├── js-spread-syntax-04-10-2022.js ├── js-static-OOP-09-05-2022.js ├── js-string-method-split-17-05-2022.js ├── js-template-literals-02-05-2022.js ├── js-ternary-04-04-2022.js ├── js-the-date-constructor-24-02-2022.js ├── js-try-catch-12-04-2022.js ├── js-typeof-operator-15-03-2022.js ├── react-accessing-the-dom-13-09-2022.jsx ├── react-api-intro-15-06-2022.html ├── react-colocating-state-06-09-2022.jsx ├── react-custom-jsx-component-23-06-2022.html ├── react-custom-styling-12-07-2022.jsx ├── react-error-boundary-30-09-2022.jsx ├── react-form-intro-14-07-2022.jsx ├── react-form-useRef-19-07-2022.jsx ├── react-fragment-01-07-2022.html ├── react-http-request-15-09-2022.jsx ├── react-http-requests-handling-errors.20-09-2022.jsx ├── react-http-requests-state-object-27-09-2022.jsx ├── react-http-requests-status-22-09-2022.jsx ├── react-introduction-to-useEffect-09-08-2022.jsx ├── react-key-prop-21-07-2022.jsx ├── react-lazy-initial-state-11-08-2022.jsx ├── react-lifting-state-up-23-08-2022.jsx ├── react-propTypes-28-05-2022.html ├── react-spreading-props-21-06-2022.html ├── react-styling-07-07-2022.jsx ├── react-styling-with-css-modules-25-08-2022.jsx ├── react-use-effect-dependency-array-16-08-2022.jsx ├── react-useReducer-basics-20-10-2022.jsx ├── react-useReducer-setState-object-28-10-2022.jsx ├── react-useState-28-07-2022.jsx ├── react-useState-initialProp-04-08-2022.jsx ├── react-useState-timer-02-08-2022.jsx ├── react-useStateWithLocalStorage-custom-hook-18-08-2022.jsx ├── ts-built-in-types-and-primitives.ts ├── ts-custom-types-using-type-aliases-08-11-2022.ts ├── ts-custom-types-with-interfaces-03-11-2022.ts ├── ts-enum-types-17-11-2022.ts ├── ts-function-arguments-04-05-2022.ts ├── ts-generics-11-05-2022.ts ├── ts-generics-constraints-08-12-2022.ts ├── ts-generics-revisited-01-12-2022.ts └── ts-typing-functions-22-11-2022.ts /README.md: -------------------------------------------------------------------------------- 1 | # Tommie's code snippets 2 | 3 | A repository to run code snippets. 4 | 5 | --- 6 | 7 | ## Index 8 | 9 | - [Stack](#stack) 10 | - [Summary](#summary) 11 | - [Getting Started](#getting-started) 12 | - [Local Commands](#local-commands) 13 | 14 | --- 15 | 16 | ## Stack 17 | 18 | - [HTML5](https://html.com/) 19 | - [CSS3](https://developer.mozilla.org/en-US/docs/Web/CSS) 20 | - [JavaScript ES6](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 21 | - [TypeScript](https://www.typescriptlang.org/) 22 | 23 | --- 24 | 25 | ## Summary 26 | 27 | | Topic | Programming Language | Description | Links | 28 | | :-------------------------------------------------------: | :---------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | 29 | | `static` keyword | JavaScript | Using the JS static keyword in OOP classes | [Twitter post](https://twitter.com/TommiEng/status/1523736644616359936) and [Raw code](/snippets/js-static-OOP-09-05-2022.js) | 30 | | Promises | JavaScript | Two different ways to call API endpoints | [Twitter post](https://twitter.com/TommiEng/status/1521631124656635906) and [Raw code](/snippets/js-promise-async-await-then-03-05-2022.js) | 31 | | Promises | JavaScript | Promise chaining and .then keyword | [Twitter post](https://twitter.com/TommiEng/status/1528753221749153794) and [Raw code](/snippets/js-promise-then-chaining-23-05-2022.js) | 32 | | Promises | JavaScript | Async await syntactic sugar | [Twitter post](https://twitter.com/TommiEng/status/1529182569325121536) and [Raw code](/snippets/js-promise-async-await-syntactic-sugar-24-05-2022.js) | 33 | | `Promise.all` | JavaScript | Run multiple promises in parallel, and wait for all of them to finish | [Twitter post](https://twitter.com/TommiEng/status/1530633767970275330) and [Raw code](/snippets/js-promise-all-28-05-2022.js) | 34 | | Rejecting a promise | JavaScript | Rejecting a promise if we have a network error, or a problem with the data we fetch from the server | [Twitter post](https://twitter.com/TommiEng/status/1531331593704554496) and [Raw code](/snippets/js-promise-reject-30-05-2022.js) | 35 | | `try...catch...finally` | JavaScript | Executing code using the `catch` or `finally` block | [Twitter post](https://twitter.com/TommiEng/status/1532042609283170306) and [Raw code](/snippets/js-catch-finally-31-05-2022.js) | 36 | | Promises | JavaScript | What is a Promise? | [Twitter post](https://twitter.com/TommiEng/status/1527745975783129088) and [Raw code](/snippets/js-promise-introduction-20-05-2022.js) | 37 | | String method split | JavaScript | Split a string into an array of strings | [Twitter post](https://twitter.com/TommiEng/status/1526638679560798215) and [Raw code](/snippets/js-string-method-split-17-05-2022.js) | 38 | | Type function arguments | TypeScript | Typing your function arguments | [Twitter post](https://twitter.com/TommiEng/status/1521920077637029889) and [Raw code](/snippets/ts-function-arguments-04-05-2022.ts) | 39 | | Creating DOM nodes | HTML, JavaScript | Creating and appending DOM nodes in HTML with JavaScript | [Twitter post](https://twitter.com/TommiEng/status/1536731373842702337?cxt=HHwWgoC90dzCyNMqAAAA) and [Raw code](/snippets/js-create-append-dom-node-14-06-2022.html) | 40 | | Intro to React API | HTML, JavaScript, React | Creating an element using the React API | [Twitter post](https://twitter.com/TommiEng/status/1537117388331794432?cxt=HHwWgIC-2dyH-NQqAAAA) and [Raw code](/snippets/react-api-intro-15-06-2022.html) | 41 | | Intro to JSX | HTML, JavaScript, React | Using JSX instead of the React API | [Twitter post](https://twitter.com/TommiEng/status/1537487443447975936?cxt=HHwWgMC4leKroNYqAAAA) and [Raw code](/snippets/js-babel-16-06-2022.html) | 42 | | Intro to JSDoc | JavaScript | Documenting complex functions with JSDoc | [Twitter post](https://twitter.com/TommiEng/status/1526266768808869894) and [Raw code](/snippets/js-doc-calculate-tip-16-05-2022.js) | 43 | | The Map object | JavaScript | Learning about the Map object and its key-value pairs | [Twitter post](https://twitter.com/TommiEng/status/1525185808122232834) and [Raw code](/snippets/js-map-object-13-05-2022.js) | 44 | | Built-in types and primitives | TypeScript | Introduction to TypeScript | [Twitter post](https://twitter.com/TommieNg/status/1587476768172171265) and [Raw code](/snippets/ts-built-in-types-and-primitives.ts) | 45 | | Interfaces | TypeScript | Making your own custom types with Interfaces | [Twitter post](https://twitter.com/TommieNg/status/1588228449725988867) and [Raw code](/snippets/ts-custom-types-with-interfaces-03-11-2022.ts) | 46 | | Generics | TypeScript | Generics | [Twitter post](https://twitter.com/TommieNg/status/1524476938823286785) and [Raw code](/snippets/ts-generics-11-05-2022.ts) | 47 | | Define custom types with type aliases | TypeScript | Another way of creating custom types | [Twitter post](https://twitter.com/TommiEng/status/1524476938823286785) and [Raw code](/snippets/ts-generics-11-05-2022.ts) | 48 | | Enums | TypeScript | Enums, or enumerable types, are a special kind of type that holds a list of hardcoded values. Once you define an enum, you can refer to it like any other regular type. | [Twitter post](https://twitter.com/TommieNg/status/1593308974266433538) and [Raw code](/snippets/ts-enum-types-17-11-2022.ts) | 49 | | Typing your functions | TypeScript | Previously, we learned on applying type information to variables. Functions are also an important part of JavaScript development, so let's learn how to type them too! | [Twitter post](https://twitter.com/TommieNg/status/1595102796122030082) and [Raw code](/snippets/ts-typing-functions-22-11-2022.ts) | 50 | | Generics (reviewed) | TypeScript | A generic type is a representation of any type that you’ll substitute in. | [Twitter post](https://twitter.com/TommieNg/status/1598403229997420545) and [Raw code](/snippets/ts-generics-revisited-01-12-2022.ts) | 51 | | Generics constraints | TypeScript | Another feature of generics are their constraints, which lets you add more restrictions on the types that can be used as parameters in your functions. | [Twitter post](https://twitter.com/TommieNg/status/1600902668624330753) and [Raw code](/snippets/ts-generics-constraints-08-12-2022.ts) | 52 | | Spreading attributes | HTML, JavaScript, React | Spreading props/attributes in React | [Twitter post](https://twitter.com/TommiEng/status/1539291527125647360) and [Raw code](/snippets/react-spreading-props-21-06-2022.html) | 53 | | Custom components | HTML, JavaScript, React | Creating JSX custom components | [Twitter post](https://twitter.com/TommiEng/status/1540000446445764608) and [Raw code](/snippets/react-custom-jsx-component-23-06-2022.html) | 54 | | Prop types | HTML, JavaScript, React | Typechecking with prop-types | [Twitter post](https://twitter.com/TommiEng/status/1541856205437648899) and [Raw code](/snippets/react-propTypes-28-05-2022.html) | 55 | | React fragments | HTML, JavaScript, React | Using React fragments | [Twitter post](https://twitter.com/TommiEng/status/1542935222781607938?cxt=HHwWhICwlaHazekqAAAA) and [Raw code](/snippets/react-fragment-01-07-2022.html) | 56 | | Intro to React styling | React, CSS | Primary way to style in React | [Twitter post](https://twitter.com/TommiEng/status/1545085781148057601) and [Raw code](/snippets/react-styling-07-07-2022.jsx) | 57 | | React custom styling | React, CSS | Styling with custom components and props | [Twitter post](https://twitter.com/TommiEng/status/1546899783251640322) and [Raw code](/snippets/react-custom-styling-12-07-2022.jsx) | 58 | | React form - Intro | React | Introduction to React forms | [Twitter post](https://twitter.com/TommiEng/status/1547656068460732421) and [Raw code](/snippets/react-form-intro-14-07-2022.js) | 59 | | React form - useRef | React | Getting a value from an input with a ref | [Twitter post](https://twitter.com/TommiEng/status/1549474947306774528) and [Raw code](/snippets/react-form-useRef-19-07-2022.jsx) | 60 | | React key prop | React | Keeping track of an element with the key prop | [Twitter post](https://twitter.com/TommiEng/status/1550187678259453958?cxt=HHwWjIC9nd3er4MrAAAA) and [Raw code](/snippets/react-key-prop-21-07-2022.jsx) | 61 | | `useState` | React | The `useState `hook | [Twitter post](https://twitter.com/TommiEng/status/1552811283388547074) and [Raw code](/snippets/react-useState-28-07-2022.jsx) | 62 | | `useState` (continued) | React | Example from the Twitter thread on the hook | [Twitter thread](https://twitter.com/TommiEng/status/1554523718654857218) and [Raw code](/snippets/react-useState-timer-02-08-2022.jsx) | 63 | | `useState` — passing an initial state prop | React | Here's a way to make our Toggle component accept an initialState prop. Then, we can initialize our state with that value. | [Twitter post](https://twitter.com/TommiEng/status/1555250681593974784) and [Raw code](/snippets/react-useState-initialProp-04-08-2022.jsx) | 64 | | `useEffect` — Introduction | React | The `useEffect` hook allows you to execute some code after React finishes rendering, or re-rendering the component to the DOM. It accepts a callback function as an argument, which will be called by React after the DOM has finished updating. | [Twitter post](https://twitter.com/TommiEng/status/1557072922493259777) and [Raw code](/snippets/react-introduction-to-useEffect-09-08-2022.jsx) | 65 | | `useState` — Lazy initial state | React | The `useState` hook will also let you pass an anonymous function, so that the hook can only call that anonymous function to get the value from the state, only when your component is being rendered for the first time in your app. | [Twitter post](https://twitter.com/TommiEng/status/1557761362264195073?cxt=HHwWgoCwqZTto54rAAAA) and [Raw code](/snippets/react-lazy-initial-state-11-08-2022.jsx) | 66 | | `useEffect` — the dependency array | React | useEffect lets you pass a second argument, which is the dependency array. This tells React that the callback function in your `useEffect` should only be called when the dependencies changed. | [Twitter post](https://twitter.com/TommiEng/status/1559583339371282436) and [Raw code](/snippets/react-use-effect-dependency-array-16-08-2022.jsx) | 67 | | Custom hook — `useState` with `localStorage` | React | In JavaScript, you'd store your reusable logic in functions. In React, if some logic inside a component can be reused in other components, you'd create what we call a custom hook! | [Twitter post](https://twitter.com/TommiEng/status/1560364993190805506) and [Raw code](/snippets/react-useStateWithLocalStorage-custom-hook-18-08-2022.jsx) | 68 | | Lifting state up | React | How to share state between sibling components? Lift it up 🏋️‍♀️ Find a lowest common parent shared between the components and add the state management there. Then, pass the state and a way to update that state down in the needed components. | [Twitter post](https://twitter.com/TommiEng/status/1562134884377710592) and [Raw code](/snippets/react-lifting-state-up-23-08-2022.jsx) | 69 | | CSS modules | React | "By creating a CSS file with the `.module.css` extension, you'll have created a module where you can't access the classes without importing. To use the class name, you can default import the "classes" object from the `.module.css` file, and then use the JSX expression `{classes.[insertYourCSSClassHere]}` to use the styling! It prevents classes with the same name from overlapping with each other by using name mangling." — [Khanh](https://twitter.com/khanhtncva) | [Twitter post](https://twitter.com/TommiEng/status/1562894435221852167) and [Raw code](/snippets/react-styling-with-css-modules-25-08-2022.jsx) | 70 | | State colocation | React | A week ago, we talked about how to lift state up in React. Today, let's discuss pushing state down, or colocating state! I like how educator [Kent C. Dodds](https://twitter.com/kentcdodds) describes it: "_Place code as close to where it's relevant as possible_". | [Twitter post](https://twitter.com/TommiEng/status/1567208594201788423) and [Raw code](/snippets/react-colocating-state-06-09-2022.jsx) | 71 | | Integrating UI libraries that works directly with the DOM | React | Some UI libraries work with the DOM directly. In JSX, `
hi
` is syntactic sugar for `React.createElement("div", null, "hi")`. We don't have access to DOM nodes in our function component. DOM nodes aren't created at all until the `ReactDOM.render` method is called. Functional components are responsible for creating our React elements and it’s bad practice to interact directly with the DOM in React. To access the DOM, ask React to give you access to a DOM node when it renders your component. This happens with the prop named `ref`. | [Twitter post](https://twitter.com/TommiEng/status/1569774903141736449) and [Raw code](/snippets/react-accessing-the-dom-13-09-2022.jsx) | 72 | | HTTP requests | React | When building apps, you’ll find yourself needing another kind of side-effect: API calls, or HTTP requests. This is pretty similar to our previous example of side-effects in interacting with the DOM, or using APIs like localStorage. What those have in common is that they all work with the `useEffect` hook. I personally found it simpler to use the Promise-based `.then` statement rather than using the `async`/`await` syntax, but it's really up to you how you'd rather do it. | [Twitter post](https://twitter.com/TommiEng/status/1570811589540052993) and [Raw code](/snippets/react-http-request-15-09-2022.jsx) | 73 | | HTTP requests — handling errors | React | Mistakes inevitably happen and errors will need handling so users don't get confounded. When handling Promise errors, there are different options like using the `.catch` statement or using the second argument of the Promised-based `.then` statement. When using the `.catch` statement, you handle errors in the Promise. However, you also handle an error in the `setWinners(data)` call, because of our Promises work. When using the second argument of the `.then` statement, you catch errors that happens in the `fetch` only. In our example, I thought calling `setWinners` would not throw an error because React handles it, so I tried the second argument way of doing it. | [Twitter post](https://twitter.com/TommiEng/status/1572329881559617536) and [Raw code](/snippets/react-http-requests-handling-errors.20-09-2022.jsx) | 74 | | HTTP requests status | React | Help your user understand the state of your application by implementing a status state for your API call. By adding a state to represent the status of our components' explicitly, you won't have to worry about what state you might get, and how to show it for a particular case, and when to set or not set it for other use cases. Here are examples of possible states we can work with: **idle**: _No request has been sent._, **ending**: _Started request_, **resolved**: _Successful request._, **rejected**: _Failed request._ | [Twitter post](https://twitter.com/TommiEng/status/1573045780566650880) and [Raw code](/snippets/react-http-requests-status-22-09-2022.jsx) | 75 | | Putting your HTTP request state in an object | React | In the [previous snippet](/snippets/react-http-requests-status-22-09-2022.jsx), you might've noticed that a bunch of different `setState`s are called simultaneously, which would not be an issue, because React 17 and lower can batch all those calls together, but not when they’re async. 😅 The good news is that, since React 18, the batching for asynchronous automatic batching is available. Even though that new feature is available, it’s better to group those related states together in an object instead of creating individual different states. P.S.: I removed the error state just for the sake of readability. | [Twitter post](https://twitter.com/TommiEng/status/1574825871482961921) and [Raw code](/snippets/react-http-requests-state-object-27-09-2022.jsx) | 76 | | Error Boundaries | React | We managed to catch errors if there happens to be one in our HTTP request, huzzah! Unfortunately, there are many other errors that might happen in applications. 🙁 You try handling those errors, but your app won’t always behave, and decides to go wild unleashing errors like a Pandora’s box. 📦 If your app throws an error and you don’t handle it, your app will be removed from the web page, and your user will be left will a blank screen. 😬 | [Twitter post](https://twitter.com/TommieNg/status/1575881137762992128) and [Raw code](/snippets/react-error-boundary-30-09-2022.jsx) 77 | | Intro to the `useReducer` hook | React | When using the `useState` hook, you can manage the state in your app. However, there might be times where you might want to separate the state's logic from the components that make the state's changes. With many parts of the state that change simultaneously, an object with those parts of the state inside can help make it more organized. That’s where `useReducer` can be of help. 💡 Normally, the `useReducer` hook would be used with a state object, but let’s start with a little gelato counter to help understand the difference between the hook's conventions and the API. Our gelatoReducer takes 2 arguments: The current state, and an "action" that the dispatch function (that'd be `setGelatoAmount`) is called with. The `useReducer hook` for our little `` component might look like over engineering, but it’s just for the sake of the example! 🍨 | [Twitter post](https://twitter.com/TommieNg/status/1583153943068446720) and [Raw code](/snippets/react-useReducer-basics-20-10-2022.jsx) | | 78 | | Setting state with useReducer | React | With class components, instead of using the “setState” hook directly, you would use `this.setState`. This is because in class components, states are handled as objects. You can call it with any amount of properties, and those same properties would be the ones updated. In this example, we mimic the same way that same way of doing setState in class components and modify the reducer. | [Twitter post](https://twitter.com/TommieNg/status/1586025057004158976) and [Raw code](/snippets/react-useReducer-setState-object-28-10-2022.jsx) | 79 | | Constructors | JavaScript | Constructors in JS | [Twitter post](https://twitter.com/TommiEng/status/1522309640570257409) and [Raw code](/snippets/js-constructors-05-05-2022.js) | 80 | | Setters and Getters | JavaScript | JS class with a setter and getter | [Twitter post](https://twitter.com/TommiEng/status/1522645848638828544) and [Raw code](/snippets/js-oop-setter-getter-06-05-2022.js) | 81 | | Template Literals | JavaScript | Template literals for string interpolation or multi-lined strings | [Twitter post](https://twitter.com/TommiEng/status/1521195466460966913) and [Raw code](/snippets/js-template-literals-02-05-2022.js) | 82 | | getComputedStyle | JavaScript | getComputedStyle method to return an object containing an element's CSS properties. | [Twitter post](https://twitter.com/TommiEng/status/1520147838914768896) and [Raw code](/snippets/js-getComputedStyle-29-04-2022.html) | 83 | | Math.floor | JavaScript | Simple example of the `Math.floor()` method | [Twitter post](https://twitter.com/TommiEng/status/1519021253532827651) and [Raw code](/snippets/js-math-floor-26-04-2022.js) | 84 | | Nullish coalescing operator | JavaScript | Using the Nullish coalescing operator `??` | [Twitter post](https://twitter.com/TommiEng/status/1517563647735779328) and [Raw code](/snippets/js-nullish-coalescing-operator-22-04-2022.js) | 85 | | Arrow functions | JavaScript | Arrow functions in JS `=>` | [Twitter thread](https://twitter.com/TommiEng/status/1517176373864980483) and [Raw code](/snippets/js-arrow-functions-21-04-2022.js) | 86 | | Logical OR assignment | JavaScript | Logical OR assignment in JS | [Twitter post](https://twitter.com/TommiEng/status/1516809407941726208) and [Raw code](/snippets/js-logical-or-assignment-20-04-2022.js) | 87 | | Logical AND assignment | JavaScript | Logical AND assignment in JS `&&=` | [Twitter post](https://twitter.com/TommiEng/status/1516464746354155520) and [Raw code](/snippets/js-logical-and-assignment-19-04-2022.js) | 88 | | Logical AND assignment | JavaScript | Logical AND assignment in JS `&&=` | [Twitter post](https://twitter.com/TommiEng/status/1516464746354155520) and [Raw code](/snippets/js-logical-and-assignment-19-04-2022.js) | 89 | | Emptying an array | JavaScript | Empty an array in JS | [Twitter post](https://twitter.com/TommiEng/status/1515056445275971593) and [Raw code](/snippets/js-empty-array-15-04-2022.js) | 90 | | Factorial (recursive) | JavaScript | Intro to recursion with a factorial function | [Twitter thread](https://twitter.com/TommiEng/status/1514640784947126285) and [Raw code](/snippets/js-recursive-factorial-14-04-2022.js) | 91 | | try...catch | JavaScript | The try...catch statement | [Twitter post](https://twitter.com/TommiEng/status/1513919158005735429) and [Raw code](/snippets/js-try-catch-12-04-2022.js) | 92 | | Promise with `setTimeout` | JavaScript | Making your JavaScript wait for a specific amount of seconds. | [Twitter post](https://twitter.com/TommiEng/status/1513548511685619714) and [Raw code](/snippets/js-promise-setTimeout-11-04-2022.js) | 93 | | Math object (min, max) | JavaScript | Using the `Math.min()` and `Math.max()` object | [Twitter post](https://twitter.com/TommiEng/status/1512495469263564816) and [Raw code](/snippets/js-math-max-min-08-04-2022.js) | 94 | | Set | JavaScript | Using Set in JS object | [Twitter thread](https://twitter.com/TommiEng/status/1512128604724998144) and [Raw code](/snippets/js-set-07-04-2022.js) | 95 | | Merging arrays | JavaScript | Merging arrays with the spread operator | [Twitter post](https://twitter.com/TommiEng/status/1511751479123755011) and [Raw code](/snippets/js-merge-arrays-06-04-2022.js) | 96 | | Remove duplicates | JavaScript | How to remove duplicates inside your array. | [Twitter post](https://twitter.com/TommiEng/status/1511401927053041669) and [Raw code](/snippets/js-remove-duplicates-array-05-04-2022.js) | 97 | | Ternary | JavaScript | Using the ternary operator in JS. | [Twitter post](https://twitter.com/TommiEng/status/1511035681254084611) and [Raw code](/snippets/js-ternary-04-04-2022.js) | 98 | | Destructuring objects | JavaScript | Destructuring objects in JS | [Twitter thread](https://twitter.com/TommiEng/status/1509953546489266181) and [Raw code](/snippets/js-destructuring-objects-01-04-2022.js) | 99 | | Transgender flag 🏳️‍⚧️ | CSS | Styles for the transgender flag | [Twitter post](https://twitter.com/TommiEng/status/1509574918261858304) and [Raw code](/snippets/css-trans-flag-31-03-2022.css) | 100 | | Array destructuring | JavaScript | Destructuring with arrays | [Twitter post](https://twitter.com/TommiEng/status/1509236791890620428) and [Raw code](/snippets/js-array-destructuring-30-03-2022.js) | 101 | | `Object.entries` | JavaScript | The `Object.entries` returns an array of arrays with a key and a value. | [Twitter post](https://twitter.com/TommiEng/status/1508850518629789702) and [Raw code](/snippets/js-object-entries-29-03-2022.js) | 102 | | Reverse a string | JavaScript | How to reverse a string with comments to the code snippet on each individual step to help break it down. | [Twitter post](https://twitter.com/TommiEng/status/1508474498470846468) and [Raw code](/snippets/js-reverse-string-28-03-2022.js) | 103 | | `Object.values` | JavaScript | How the `Object.values` method returns an array of your object's properties. | [Twitter post](https://twitter.com/TommiEng/status/1507764397678206983) and [Raw code](/snippets/js-object-values-26-03-2022.js) | 104 | | `Object.keys` | JavaScript | Use `Object.keys()` to collect all the key names from any object. This can be useful once you obtain the array, because you're then able to loop through it! | [Twitter post](https://twitter.com/TommiEng/status/1507432271351107589) and [Raw code](/snippets/js-object.keys-method-25-03-2022.js) | 105 | | Sorting arrays | JavaScript | Avoid sorting big amounts of data in the frontend. It can be an expensive operation, so it is preferable to be done in the backend. | [Twitter post](https://twitter.com/TommiEng/status/1506660726257205248) and [Raw code](/snippets/js-sorting-arrays-23-03-2022.js) | 106 | | `transform-origin` | CSS | It is used with the `transform` property to change the initial point of your transformation. Give it values such as: `right`, `bottom`, lengths, or percentages. The arguments start with the horizontal position, followed by the vertical position. | [Twitter post](https://twitter.com/TommiEng/status/1506328219812773894) and [Raw code](/snippets/css-transform-origin-property-22-03-2022.css) | 107 | | `aspect-ratio` | CSS | Use the `aspect-ratio` property to keep your boxes' dimensions proportional to each other using a ratio. It accepts a ratio as its argument in width/height form. | [Twitter post](https://twitter.com/TommiEng/status/1505988148060295168) and [Raw code](/snippets/css-aspect-ratio-21-03-2022.css) | 108 | | Falsy values | JavaScript | JavaScript tends to evaluate the type of values to Boolean when working with conditional statements such as `if`...`else`, or loops like `do`...`while`. Here are examples of possible falsy values. | [Twitter post](https://twitter.com/TommiEng/status/1504834490283311107) and [Raw code](/snippets/js-falsy-values-18-03-2022.js) | 109 | | Equality and strict equality operator | JavaScript | The biggest difference between the equality (`==`) and strict equality (`===`) is that the equality operator tries to compare and convert variables that have different types, whereas the strict equality operator does not try to convert types. | [Twitter post](https://twitter.com/TommiEng/status/1504501469906616325) and [Raw code](/snippets/js-equality-operators-17-03-2022.js) | 110 | | Converting a `String` to a `Number` | JavaScript | A brief example on how to convert `String`s to `Number`s using either JavaScript's `Number` constructor, or the `parseInt` function. This can be useful when trying to take a value from the user's input in a form, but you want it as a `Number` instead. | [Twitter post](https://twitter.com/TommiEng/status/1504115938454552582) and [Raw code](/snippets/js-convert-string-to-number-16-03-2022.js) | 111 | | The `typeof` operator | JavaScript | Not having to assign types to variables in JS also means their types might change over time. An useful way of using it is when a variable might be undefined, and you want to catch it in that case. | [Twitter post](https://twitter.com/TommiEng/status/1503750761313968147) and [Raw code](/snippets/js-typeof-operator-15-03-2022.js) | 112 | | `clamp()` | CSS | The `clamp` function will clamp your element's value between your given minimum value, maximum value, based on your ideal value. This function is useful when working with fluid typography, aka when you want your font-size to reflect the screen size. | [Twitter post](https://twitter.com/TommiEng/status/1503418174376759300) and [Raw code](/snippets/css-clamp-function-14-03-2022.css) | 113 | | `min()` and `max()` | CSS | Think of the `min()` as a function that returns the maximum value that your element's property can have, and vice-versa for the `max()` function. | [Twitter post](https://twitter.com/TommiEng/status/1503056222261551107) and [Raw code](/snippets/css-min-max-function-13-03-2022.css) | 114 | | Combining `filter` functions | CSS | Did you know that you can combine CSS `filter` functions together? The possibilities are endless. | [Twitter post](https://twitter.com/TommiEng/status/1502360892813594627) and [Raw code](/snippets/css-combining-filter-functions-11-03-2022.css) | 115 | | `while` vs. `do...while` | JavaScript | Here's a brief example below about the `do...while` vs. `while` loop statements. Cases where you want to prompt a game once is great for a `do...while` statement, because the game will appear at least once, while the user doesn't quit. | [Twitter post](https://twitter.com/TommiEng/status/1501990541180944399) and [Raw code](/snippets/js-do-while-vs-while-loop-10-03-2022.js) | 116 | | `innerText` | JavaScript | Forgot to insert text in your HTML document? Have no fear, JavaScript `HTMLElement.innerText` is here! 🦸‍♀️ Prioritize using this property instead of the innerHTML property to avoid external cross-site scripting (XSS) attacks on your page. 🛡️ | [Twitter post](https://twitter.com/TommiEng/status/1501664631504449540) and [Raw code](/snippets/js-HTMLElement-innerText-09-03-2022.js) | 117 | | `grayscale()` | CSS | This function will accept a length, or a percentage as its argument, giving you that dark, eerie, and beautiful feel to your now monochrome elements. | [Twitter post](https://twitter.com/TommiEng/status/1501245138458353667) and [Raw code](/snippets/css-filter-grayscale-08-03-2022.css) | 118 | | ` contrast()` | CSS | Bring out the colors on your elements with the CSS `contrast()` function. I like to use it to make the colors on my images more intense, or tone it down by giving it a lower value. This function accepts a number, or a percentage as an argument. | [Twitter post](https://twitter.com/TommiEng/status/1500945089492922380) and [Raw code](/snippets/css-filter-constrast-07-03-2022.css) | 119 | | `blur()` | CSS | Blur the lines on your elements with the CSS `blur()` function. This function will accept a length as its argument. | [Twitter post](https://twitter.com/TommiEng/status/1499814956287631364) and [Raw code](/snippets/css-filter-blur-04-03-2022.css) | 120 | | `brightness()` | CSS | Shed some light on your elements with the CSS `brightness()` function. It takes a number, or a percentage as an argument. That argument is then multiplied by the default value of 1 for your desired light intensity. 💡 | [Twitter post](https://twitter.com/TommiEng/status/1499452518534979588) and [Raw code](/snippets/css-filter-brightness-03-03-2022.css) | 121 | | The `lorem` Emmet abbreviation | HTML | Don't know what to write? This Emmet abbreviation is pretty useful for summoning dummy text. Simply start typing "lorem", and add a number to specify the number of words you want in your paragraph. 📜 | [Twitter post](https://twitter.com/TommiEng/status/1499034725754806288) and [Raw code](/snippets/html-lorem-emmet-02-03-2022.html) | 122 | | The `HTML` template Emmet shortcut | HTML | I recently learned a new fun Emmet shortcut to quickly generate a HTML template using only the exclamation point (`!`) symbol ❗️ | [Twitter post](https://twitter.com/TommiEng/status/1498699503892840452) and [Raw code](/snippets/html-template-emmet-01-03-2022.html) | 123 | | The `HTML` markup Emmet shortcut | HTML | It is possible to use Emmet abbreviations to generate your markup quickly. They are similar to CSS selectors. In the related code snippet, you can see how to generate markup quickly and avoid repetition. | [Twitter post](https://twitter.com/TommiEng/status/1498377857650892805) and [Raw code](/snippets/html-generate-markup-with-emmet-28-02-2022.html) | 124 | | The `Date` constructor | JavaScript | Use the new Date() constructor to get back a `Date` object, like in the example below. 📅 | [Twitter post](https://twitter.com/TommiEng/status/1496872381092147210) and [Raw code](/snippets/js-the-date-constructor-24-02-2022.js) | 125 | | transform: `skew` | CSS | The `skew()` function is used to distort elements, taking degrees as its arguments for the its x-axis and y-axis. Elements with class `.nachos` will skew 10% of a turn on the x-axis, while `.pierogi` will skew 10 degrees on the x-axis and 20 degrees on the y-axis. | [Official post](https://twitter.com/TommiEng/status/1496557133709643776), [sketch](https://twitter.com/khanhtncva/status/1496804656894574599), and [raw code](/snippets/css-transform-skew-23-02-2022.css) | 126 | | transform: `rotate` | CSS | Use the `rotate()` function to tilt around your elements. It accepts an angle in degrees as its argument. In the related code snippet, elements with the `.bunny` class will rotate 90 degrees to the right. | [Official post](https://twitter.com/TommiEng/status/1495800030233567238), [sketch](https://twitter.com/TommiEng/status/1495826857148698627), and [raw code](/snippets/css-transform-rotate-21-02-2022.css) | 127 | | transform: `translate` | CSS | Use the `translate()` function to position your elements. It accepts x, y lengths as its values. In the related code snippet, the `div` tag will move 100% of its width to the right 👉. The `p` tag will move 10px to the right 👉, and 20px downwards 👇. | [Official post](https://twitter.com/TommieNg/status/1495096689643991043), and [raw code](/snippets/css-transform-translate-19-02-2022.css) | 128 | | Spread syntax `...` | JavaScript | Spreading `...` can be useful in JS when you need to copy objects' properties or elements within an array. Use it to dynamically create your objects and arrays. | [Official post](https://twitter.com/TommieNg/status/1577376539552923665), and [raw code](/snippets/js-spread-syntax-04-10-2022.js) | 129 | | Rest parameters | JavaScript | You don't know how many arguments your function will need? Try the rest params syntax! If you recall the post on the spread syntax, you might notice they look similar. Funny thing is, they're actually opposites! The rest parameter syntax is a way to catch any remaining variables we didn't account for. It's useful to think of it as they are unlimited amounts of arguments to a function. The way to indicate that is with the `...` notation. | [Official post](https://twitter.com/TommieNg/status/1578440685576781825), and [raw code](/snippets/js-rest-parameters-07-10-2022.js) | 130 | 131 | --- 132 | 133 | ## Getting Started 134 | 135 | Fork or clone the repository. 136 | 137 | --- 138 | 139 | ## Local Commands 140 | 141 | In this current section, you can find the command to run the code snippet in your machine: 142 | 143 | ```sh 144 | $ node 145 | ``` 146 | 147 | --- 148 | 149 | ## Contributing 150 | 151 | 1. Fork it 152 | 2. Create your feature branch with specs (`git checkout -b my-cute-feature`). 153 | 3. Commit your changes (`git commit -m 'Added my cute feature'`). 154 | 4. Push to the branch (`git push origin my-cute-feature`). 155 | 5. Create your new pull request. 156 | 157 | --- 158 | 159 | ## Contributors 160 | 161 | 162 | 163 | 164 | 166 |

Tommie Nguyễn


Gui Bibeau

165 |
167 | 168 | --- 169 | 170 | # **Have a question or suggestion?** 171 | 172 | Contact me on [Twitter](https://twitter.com/TommiEng), send an email to TommiEng@proton.me, or create a pull request on this project. 173 | 174 | --- 175 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "tommie-snippets", 3 | "description": "A collection of snippets from TommiEng", 4 | "version": "0.0.1", 5 | "private": false, 6 | "devDependencies": {} 7 | } 8 | -------------------------------------------------------------------------------- /snippets/css-aspect-ratio-21-03-2022.css: -------------------------------------------------------------------------------- 1 | div { 2 | aspect-ratio: 3/1; 3 | } 4 | /* The div's width is three times its height */ 5 | 6 | p { 7 | aspect-ratio: 1/1; 8 | } 9 | /* The p element becomes a perfect square */ -------------------------------------------------------------------------------- /snippets/css-clamp-function-14-03-2022.css: -------------------------------------------------------------------------------- 1 | div { 2 | font-size: clamp(1rem, 5vw, 3rem); 3 | } 4 | 5 | /* 6 | Clamp takes a minimum value, an ideal value, and a maximum value. 7 | */ -------------------------------------------------------------------------------- /snippets/css-combining-filter-functions-11-03-2022.css: -------------------------------------------------------------------------------- 1 | div { 2 | filter: brightness(2) contrast(50%); 3 | } 4 | 5 | span { 6 | filter: brightness(25%) grayscale(0.5) blur(3px); 7 | } -------------------------------------------------------------------------------- /snippets/css-filter-blur-04-03-2022.css: -------------------------------------------------------------------------------- 1 | /* Default value of the blur() function */ 2 | div { 3 | filter: blur(0); 4 | } 5 | 6 | /* Using length in pixels as a value */ 7 | p { 8 | filter: blur(3px); 9 | } 10 | 11 | /* Rem units also work, as long as it's a length */ 12 | span { 13 | filter: blur(5rem); 14 | } 15 | -------------------------------------------------------------------------------- /snippets/css-filter-brightness-03-03-2022.css: -------------------------------------------------------------------------------- 1 | /* Default brightness of 1 */ 2 | div { 3 | filter: brightness(1); 4 | } 5 | 6 | /* 1.5 times brighter */ 7 | p { 8 | filter: brightness(1.5); 9 | } 10 | 11 | /* Only 25% of the default brightness, which making it darker */ 12 | span { 13 | filter: brightness(25%); 14 | } 15 | -------------------------------------------------------------------------------- /snippets/css-filter-constrast-07-03-2022.css: -------------------------------------------------------------------------------- 1 | 2 | /* Default contrast value */ 3 | div { 4 | filter: contrast(1); 5 | } 6 | 7 | /* Half of the default contrast */ 8 | span { 9 | filter: contrast(50%); 10 | } 11 | 12 | /* Twice the default contrast */ 13 | p { 14 | filter: contrast(1.5); 15 | } 16 | -------------------------------------------------------------------------------- /snippets/css-filter-grayscale-08-03-2022.css: -------------------------------------------------------------------------------- 1 | /* 2 | The default value of grayscale, 3 | meaning the original colors are kept. 4 | */ 5 | div { 6 | filter: grayscale(0); 7 | } 8 | 9 | /* 10 | The span element will be grayed out 11 | at half of its maximum capacity of 100%. 12 | */ 13 | span { 14 | filter: grayscale(50%); 15 | } 16 | 17 | /* The maximum value of grayscale. 18 | Your element should be gray now! 19 | */ 20 | p { 21 | filter: grayscale(1); 22 | } 23 | -------------------------------------------------------------------------------- /snippets/css-min-max-function-13-03-2022.css: -------------------------------------------------------------------------------- 1 | /* 2 | The maximum width that the div element can have is between 3 | 20vw and 900px. 20vw varies with the screen's width. 4 | */ 5 | div { 6 | width: min(50vw, 300px); 7 | } 8 | 9 | 10 | /* 11 | The span width's minimum value will be either 30vw, or 400px, depending on which width will bigger according 12 | to the max() function. 13 | */ 14 | span { 15 | width: max(30vw, 400px); 16 | } 17 | -------------------------------------------------------------------------------- /snippets/css-trans-flag-31-03-2022.css: -------------------------------------------------------------------------------- 1 | transgender-flag { 2 | background: linear-gradient( 3 | 180deg, 4 | #5BCEFA 20%, 5 | #F5A9B8 20%, 6 | 40%, 7 | #FFFFFF 40%, 8 | 60%, 9 | #F5A9B8 60%, 10 | 80%, 11 | #5BCEFA 80%); 12 | } -------------------------------------------------------------------------------- /snippets/css-transform-origin-property-22-03-2022.css: -------------------------------------------------------------------------------- 1 | div { 2 | transform-origin: center; 3 | } 4 | /* Default value */ 5 | 6 | p { 7 | transform-origin: top left; 8 | } 9 | /* The transform will be applied based on the top left corner */ 10 | 11 | span { 12 | transform-origin: 50px 60px; 13 | } 14 | /* The transform will be applied based on 15 | the origin 50px to the right, and 60px downwards */ -------------------------------------------------------------------------------- /snippets/css-transform-rotate-21-02-2022.css: -------------------------------------------------------------------------------- 1 | .bunny { 2 | transform: rotate(90deg) 3 | } -------------------------------------------------------------------------------- /snippets/css-transform-skew-23-02-2022.css: -------------------------------------------------------------------------------- 1 | .nachos { 2 | transform: skew(0.10turn) 3 | } 4 | 5 | .pierogi { 6 | transform: skew(10deg, 20deg) 7 | } -------------------------------------------------------------------------------- /snippets/css-transform-translate-19-02-2022.css: -------------------------------------------------------------------------------- 1 | div { 2 | transform: translate(100%) 3 | } 4 | 5 | p { 6 | transform: translate(10px, 20px) 7 | } -------------------------------------------------------------------------------- /snippets/html-generate-markup-with-emmet-28-02-2022.html: -------------------------------------------------------------------------------- 1 | 2 | ul>li*3 3 | -------------------------------------------------------------------------------- /snippets/html-lorem-emmet-02-03-2022.html: -------------------------------------------------------------------------------- 1 | 5 | 6 | lorem10 7 | -------------------------------------------------------------------------------- /snippets/html-template-emmet-01-03-2022.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Document 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /snippets/js-HTMLElement-innerText-09-03-2022.js: -------------------------------------------------------------------------------- 1 | // Safe way to set the text content inside your div element. 2 | const divElement = document.querySelector("div"); 3 | 4 | divElement.innerText = "You're born naked and the rest is drag."; 5 | 6 | // This property can be prone to XSS software attacks. 7 | const ulElement = document.querySelector("ul"); 8 | 9 | ulElement.innerHTML = "
  • Jujubee
  • "; 10 | -------------------------------------------------------------------------------- /snippets/js-array-destructuring-30-03-2022.js: -------------------------------------------------------------------------------- 1 | const pronouns = ["He/his", "She/hers", "They/them"]; 2 | 3 | const [male, female, nonbinary] = pronouns; 4 | 5 | console.log(nonbinary); 6 | // This outputs to the console: "They/them" 7 | -------------------------------------------------------------------------------- /snippets/js-arrow-functions-21-04-2022.js: -------------------------------------------------------------------------------- 1 | /* 2 | Arrow functions are one of the popular ES6 features. 3 | They introduced a new way of writing concise functions ➡️ 4 | 5 | Can you spot the differences between the two different ways of defining functions? 6 | If not, the main difference is the function keyword and the arrow => symbol. 7 | When we call both of them, they output the same result though! 8 | */ 9 | 10 | // Function expression 11 | function packLunch(lunch, beverage) { 12 | return [lunch, beverage]; 13 | } 14 | 15 | // Arrow function expression 16 | const packLunch = (lunch, beverage) => [lunch, beverage]; 17 | 18 | console.log(packLunch("Spaghetti 🍝", "Red wine 🍷")); 19 | // This will output to the console: ["Spaghetti 🍝", "Red wine 🍷"]; 20 | 21 | /* 22 | If you just have one parameter to pass, you’re not using rest parameters, or destructuring, parentheses are optional! 23 | If that’s not the case, include your parentheses! 24 | */ 25 | 26 | // Arrow functions with no parameters requires parentheses. 27 | const stomachStatus = () => "I'm hungry!"; 28 | 29 | // Arrow functions with a single parameter doesn't require parentheses. 30 | const dailySnack = (snack) => `Today's snack is ${snack}`; 31 | 32 | // Arrow functions with more than 1 parameter requires parentheses. 33 | const packLunch = (lunch, beverage) => [lunch, beverage]; 34 | 35 | // Arrow functions using the rest parameter. 36 | const packOnlyLeftovers = (beverage, ...leftovers) => leftovers; 37 | console.log(packOnlyLeftovers("Soy milk🥛", "Curry🍛", "Pierogi🥟")); 38 | // This outputs: ["Curry🍛", "Pierogi🥟"]. 39 | 40 | // Arrow functions using destructuring. 41 | const beverages = { 42 | juice: "Apple🍎", 43 | tea: "Green🍵", 44 | }; 45 | 46 | const packDrinks = ({ juice }) => juice; 47 | 48 | console.log(packDrinks(beverages)); 49 | // This outputs to the console: "Apple🍎" 50 | 51 | /* 52 | If you return only one line of code, you can ignore the return keyword and curly brackets. 53 | However, if the body of your function contains multiple lines, wrap it in curly brackets and include a return statement! 54 | */ 55 | // Arrow function returning a value implicitely. 56 | const cookLunch = (ingredient) => [ingredient, "Rice🍚"]; 57 | 58 | // Arrow function using curly brackets and the return keyword. 59 | const cookLunch2 = (ingredient) => { 60 | const ingredients = ["Rice🍚"]; 61 | ingredients.push(ingredient); 62 | 63 | return ingredients; 64 | }; 65 | 66 | /* 67 | Last but not least, you can also return an object. 68 | Just make sure to wrap your object in parentheses when returning it. 69 | */ 70 | 71 | const todaysLunch = () => ({ 72 | meal: "Taco🌮", 73 | dessert: "Chocolate chip cookie🍪", 74 | }); 75 | 76 | console.log(todaysLunch().meal); 77 | // This outputs to the console: "Taco🌮". 78 | -------------------------------------------------------------------------------- /snippets/js-babel-16-06-2022.html: -------------------------------------------------------------------------------- 1 | 2 |
    3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 18 | -------------------------------------------------------------------------------- /snippets/js-catch-finally-31-05-2022.js: -------------------------------------------------------------------------------- 1 | // let's imagine imagine two recipes for tacos and burrito. Maybe the recipes will be bad and cause the promises to reject. 2 | const tacosRecipe = () => 3 | new Promise((resolve) => { 4 | const isTheTacoGood = Math.floor(Math.random() * 3) + 1 > 1; 5 | setTimeout(() => { 6 | if (isTheTacoGood) { 7 | resolve("🌮"); 8 | } 9 | reject("This is not the tacos I ordered!"); 10 | }, 1000); 11 | }); 12 | 13 | const burritoRecipe = () => 14 | new Promise((resolve, reject) => { 15 | const isTheBurritoGood = Math.floor(Math.random() * 3) + 1 > 1; 16 | setTimeout(() => { 17 | if (isTheBurritoGood) { 18 | resolve("🌯"); 19 | } 20 | reject("This is not the burrito I ordered!"); 21 | }, 1000); 22 | }); 23 | 24 | // You are really hungry and you want to order tacos and burritos. 25 | const tacosBurrito = async () => { 26 | // you can use a try... catch statement to catch any errors 27 | try { 28 | const tacos = await tacosRecipe(); 29 | const burrito = await burritoRecipe(); 30 | console.log(`I ordered ${tacos} and ${burrito}`); 31 | } catch (error) { 32 | // the catch statement will catch any errors that are thrown in the promises. 33 | // this is the good moment to log these errors to a error reporting service like Sentry. 34 | console.error(error); 35 | console.error("If you can't cook tacos or burrito i'll eat salsa"); 36 | } finally { 37 | // the finally statement will always run. It is used to clean up after the promises. 38 | // you can recover from error/loading states by using the finally statement. 39 | console.log("bring me the check please!"); 40 | } 41 | }; 42 | 43 | tacosBurrito(); 44 | 45 | // advanced bits: 46 | // if a promise is rejected, .then accepts a second argument called onRejected which is a function that will be called if the promise is rejected. 47 | // this is useful to attempt a retry or to handle errors. The second argument is optional. 48 | -------------------------------------------------------------------------------- /snippets/js-constructors-05-05-2022.js: -------------------------------------------------------------------------------- 1 | // JavaScript constructors are generally known for their usage in ES6 classes. 2 | class CincoDeMayo { 3 | constructor(month, day) { 4 | this.month = month; 5 | this.day = day; 6 | } 7 | } 8 | 9 | // However, they have uses in creating different JavaScript objects. For example, they can be used to create a string! 10 | const today = new String("Cinco de Mayo!"); 11 | 12 | // Constructors can be used to transform a number to a string as well! 13 | const five = new String(5); 14 | 15 | // They can also be used for creating empty arrays! 16 | const tacos = new Array(3); 17 | const burritos = new Array(5); 18 | 19 | tacos[0] = "🌮"; 20 | // Tacos now return: ['🌮', undefined, undefined] 21 | 22 | // Or, for creating a Set or a Map object: 23 | const greeting = new Set(["Happy Cinco de Mayo!"]); 24 | 25 | const meals = new Map(); 26 | meals.set("Tamale🫔", 2); 27 | meals.set("Horchata🥛", 4); 28 | meals.set("Guacamole🥑", 10); 29 | 30 | // In JavaScript, everything is an object! This is why with these constructors, you can create an instance of the different classes the language offers you! 31 | -------------------------------------------------------------------------------- /snippets/js-convert-string-to-number-16-03-2022.js: -------------------------------------------------------------------------------- 1 | const stringSeven = "7"; 2 | // typeof stringSeven returns "string" 3 | 4 | const numSeven = parseInt(stringSeven); 5 | // typeof numSeven returns "number" 6 | 7 | const numberSeven = Number(stringSeven); 8 | // typeof numberSeven also returns "number" 9 | -------------------------------------------------------------------------------- /snippets/js-create-append-dom-node-14-06-2022.html: -------------------------------------------------------------------------------- 1 | 2 |
    3 | 12 |
    13 | -------------------------------------------------------------------------------- /snippets/js-destructuring-objects-01-04-2022.js: -------------------------------------------------------------------------------- 1 | const vietnam = { 2 | capital: "Hanoi", 3 | largestCity: "Ho Chi Minh (formerly Saigon)", 4 | currency: "Vietnamese đồng (VND)", 5 | timeZone: "UTC+07:00", 6 | drivingSide: "right", 7 | callingCode: "+84", 8 | }; 9 | 10 | // Destructuring a single variable 11 | const { capital } = vietnam; 12 | console.log(capital); 13 | 14 | // Extracting a value that does not exist in an object yet. 15 | const { abbreviation = "VN" } = vietnam; 16 | console.log(abbreviation); 17 | 18 | // Extract a value and rename it 19 | const { timeZone: tz } = vietnam; 20 | console.log(tz); 21 | 22 | // Extracting from a function 23 | const getCities = ({ capital, largestCity }) => { 24 | return `The capital is ${capital} and the largest city is ${largestCity}.`; 25 | }; 26 | console.log(getCities(vietnam)); 27 | -------------------------------------------------------------------------------- /snippets/js-do-while-vs-while-loop-10-03-2022.js: -------------------------------------------------------------------------------- 1 | // do...while statements always run the code at least once 2 | // at the beginning before entering the condition. 3 | let appleQuantity = 3; 4 | 5 | do { 6 | appleQuantity = appleQuantity - 1; 7 | } while (appleQuantity > 0); 8 | 9 | // while statements will first enter the condition first 10 | // before executing the code. 11 | let mangoQuantity = 3; 12 | 13 | while (mangoQuantity > 0) { 14 | mangoQuantity = mangoQuantity - 1; 15 | } 16 | -------------------------------------------------------------------------------- /snippets/js-doc-calculate-tip-16-05-2022.js: -------------------------------------------------------------------------------- 1 | const satisfactionTipRatio = new Map([ 2 | ["Correct", 0.1], 3 | ["Good", 0.15], 4 | ["Great", 0.2], 5 | ]); 6 | 7 | /** 8 | calculateTip is used to easily calculate tips and the total price. 9 | @param {number} price - The original price of the meal as a number. 10 | @param {string | number} qualityOrRate - A service quality string such as 'Good', 'Correct' or 'Great. 11 | You can also pass a number such as 0.25 for 25% if you want to do your own custom tip amount. 12 | @returns {number} the price to pay, plus the tip. 13 | */ 14 | const calculateTip = (price, qualityOrRate) => { 15 | // Check if the user has passed a quality or a percentage (%). 16 | if (satisfaction.has(qualityOrRate)) { 17 | // Calculate based on the pre-defined service satisfaction. 18 | return price + price * tipsQuality.get(qualityOrRate); 19 | } 20 | // If the user passes a custom tip rate, we calculate it. 21 | if (typeof qualityOrRate === "number") { 22 | return price + price * qualityOrRate; 23 | } 24 | 25 | // Return the price if the user leaves no tips. 26 | return price; 27 | }; 28 | -------------------------------------------------------------------------------- /snippets/js-empty-array-15-04-2022.js: -------------------------------------------------------------------------------- 1 | const vegetables = ["🥕", "🍆", "🥦", "🌶️", "🍄"]; 2 | 3 | // This is a way to empty your array: 4 | vegetables.length = 0; -------------------------------------------------------------------------------- /snippets/js-equality-operators-17-03-2022.js: -------------------------------------------------------------------------------- 1 | console.log(7 == "7"); 2 | // Outputs true. It is trying to convert the types to match. 3 | 4 | console.log(7 === "7"); 5 | // Outputs false. Assumes the types are initially different. 6 | -------------------------------------------------------------------------------- /snippets/js-falsy-values-18-03-2022.js: -------------------------------------------------------------------------------- 1 | // Here is an array of possible falsy values. 2 | const falsyValues = [false, 0, ``, "", "", NaN, null, undefined]; 3 | -------------------------------------------------------------------------------- /snippets/js-getComputedStyle-29-04-2022.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

    I'm a pink heading🦩

    4 | 5 | 16 | 17 | -------------------------------------------------------------------------------- /snippets/js-logical-and-assignment-19-04-2022.js: -------------------------------------------------------------------------------- 1 | let falsy = 0; 2 | let truthy = 1; 3 | let fruit = "Bananas" 4 | 5 | falsy &&= 7; 6 | // The falsy variable would remain 0, because it is a falsy value. 7 | 8 | truthy &&= 8; 9 | // The truthy variable would become 8, because it is a truthy value. 10 | 11 | fruit &&= "Strawberry"; 12 | // The fruit variable is also a truthy value, which assigns it to "Strawberry". -------------------------------------------------------------------------------- /snippets/js-logical-or-assignment-20-04-2022.js: -------------------------------------------------------------------------------- 1 | document.querySelector('.menu').textContent ||= 'Where is my menu? 🥢' 2 | 3 | /* This is a nice use of the logical OR assignment. 4 | In this example, if the HTML element with the class 'menu' contains nothing (falsy value), 5 | it will be assigned: 'Where is my menu? 🥢'. 6 | If it does contain something (truthy value), then it will not assign anything. 7 | */ -------------------------------------------------------------------------------- /snippets/js-map-object-13-05-2022.js: -------------------------------------------------------------------------------- 1 | // Creating a map is done by creating a new instance: 2 | const dogBreeds = new Map(); 3 | 4 | // A JS Map object is about holding key-value pairs. 5 | // Let’s store some dogs’ names and associate their names to their breed! 6 | dogBreeds.set("Chowmein", "Chow Chow"); 7 | // My dog Chowmein is a Chow Chow. 8 | 9 | dogBreeds.set("Goldilocks", "Golden Retriever"); 10 | // My neighbour's dog Goldilocks is a Golden Retriever. 11 | 12 | dogBreeds.set("Lassie", "Rough Collie"); 13 | // My classmate's dog Lassie is a Rough Collie. 14 | 15 | // We can check if a particular key is already in a Map object. 🗺️ 16 | dogBreeds.has("Marmaduke"); 17 | // This will return false, because Marmaduke was not previously included in dogBreeds. 18 | 19 | // We can also verify what is the value of a certain key. 🗝️ 20 | dogBreeds.get("Goldilocks"); 21 | // This will return: "Golden Retriever" 22 | 23 | // Finally, we can also iterate over all the elements of the Map object 🔂 24 | for (const dog of dogBreeds.keys()) { 25 | console.log(dogBreeds.get(dog)); 26 | } 27 | // This will return: "Chow Chow", "Golden Retriever", "Rough Collie" 28 | -------------------------------------------------------------------------------- /snippets/js-math-floor-26-04-2022.js: -------------------------------------------------------------------------------- 1 | Math.floor(0.5); // Returns 0 2 | 3 | Math.floor(3.14); // Returns 3 4 | 5 | Math.floor(-0.7); // Returns -1 6 | 7 | Math.floor(-1.23); // Returns -2 8 | -------------------------------------------------------------------------------- /snippets/js-math-max-min-08-04-2022.js: -------------------------------------------------------------------------------- 1 | Math.max(10, 20, 30, 40); 2 | // This would return 40. 3 | 4 | Math.min(10, 20, 30, 40); 5 | // This would return 10. 6 | 7 | 8 | const numbers = [50, 60, 70, 80, 90 ,100]; 9 | console.log(Math.max(...numbers)); 10 | // First, spread the numbers array in the argument, then call Math.max()! -------------------------------------------------------------------------------- /snippets/js-merge-arrays-06-04-2022.js: -------------------------------------------------------------------------------- 1 | const makeup = ["Lipstick", "Eyeliner", "Mascara", "Foundation"]; 2 | 3 | const skincare = ["Moisturizer", "Toner", "Cleanser"]; 4 | 5 | // Thanks to the spread operator, extracting elements from array can be easier! 6 | const cosmetics = [...makeup, ...skincare]; 7 | 8 | console.log(cosmetics); 9 | // This outputs: ["Lipstick", "Eyeliner", "Mascara", "Foundation", "Moisturizer", "Toner", "Cleanser"] -------------------------------------------------------------------------------- /snippets/js-nullish-coalescing-operator-22-04-2022.js: -------------------------------------------------------------------------------- 1 | const ukraineFlag = null ?? "🇺🇦"; 2 | console.log(ukraineFlag); 3 | // This will output: "🇺🇦", because null is a nullish value. 4 | 5 | const zero = undefined ?? 0; 6 | console.log(zero); 7 | // This will output: 0. undefined is a nullish value too. 8 | 9 | const browser = "Firefox🦊" ?? "Brave🦁" ?? "Chrome"; 10 | console.log(browser); 11 | // This will output "Firefox🦊", because there's no nullish values. 12 | -------------------------------------------------------------------------------- /snippets/js-object-entries-29-03-2022.js: -------------------------------------------------------------------------------- 1 | const cart = { 2 | 123: { 3 | name: "Banh mi sandwich", 4 | quantity: 4, 5 | price: 20, 6 | }, 7 | 567: { 8 | name: "Bowl of pho", 9 | quantity: 6, 10 | price: 1, 11 | }, 12 | }; 13 | 14 | const result = Object.entries(cart).map((entry) => { 15 | const key = entry[0]; 16 | const value = entry[1]; 17 | 18 | return { 19 | itemId: key, 20 | price: value.quantity * value.price, 21 | }; 22 | }); 23 | 24 | // 1. Object.entries(cart) will return: 25 | // [ 26 | // [ 27 | // "123", { 28 | // name: "Banh mi sandwich", 29 | // quantity: 4, 30 | // price: 20 31 | // } 32 | // ], 33 | // [ 34 | // "567", { 35 | // name: "Bowl of pho", 36 | // quantity: 6, 37 | // price: 1 38 | // } 39 | // ] 40 | // ] 41 | 42 | // 2. .map will be used to create a new array 43 | 44 | // 3. Destructure key to be the first value in the array, which will be "123" or "456". 45 | 46 | // 4. Destructure value to be the second value, which is the first object, or second object. 47 | 48 | // 5. Return a new object with the keys and the new object with the updated price. 49 | 50 | console.log(result); 51 | -------------------------------------------------------------------------------- /snippets/js-object-values-26-03-2022.js: -------------------------------------------------------------------------------- 1 | const rupaul = { 2 | name: "RuPaul Charles", 3 | pronouns: "He/she", 4 | occupation: "Drag Queen", 5 | }; 6 | 7 | Object.values(rupaul); 8 | // This returns: ["RuPaul Charles", "He/she", "Drag Queen"] 9 | -------------------------------------------------------------------------------- /snippets/js-object.keys-method-25-03-2022.js: -------------------------------------------------------------------------------- 1 | const tommie = { 2 | name: "Tommie", 3 | pronouns: "she/they", 4 | occupation: "Developer", 5 | }; 6 | 7 | Object.keys(tommie); 8 | // This will return: ['name', 'pronouns', 'occupation'] 9 | -------------------------------------------------------------------------------- /snippets/js-oop-setter-getter-06-05-2022.js: -------------------------------------------------------------------------------- 1 | class RoadTrip { 2 | constructor(destinations) { 3 | // Set the array of cities to visit. 4 | this.destinations = destinations; 5 | } 6 | // Start the trip at 0. 7 | _currentStep = 0; 8 | 9 | // Set the current city we are in. 10 | set current(city) { 11 | this._currentStep = this.destinations.indexOf(city); 12 | } 13 | 14 | // Get the current city. 15 | get currentCity() { 16 | return this.destinations[this._currentStep]; 17 | } 18 | 19 | // Get the next city to visit. 20 | get nextCity() { 21 | return this.destinations[this._currentStep + 1]; 22 | } 23 | } 24 | 25 | // Create an instance of RoadTrip. 26 | const trip = new RoadTrip(["NYC🗽", "Boston🍩", "Miami🌴"]); 27 | 28 | console.log(trip.currentCity); 29 | // This will output to the console: 'NYC🗽'. 30 | 31 | trip.current = trip.nextCity; 32 | // By combining the getter and setter, we move to the next city. 33 | 34 | console.log(trip.currentCity); 35 | // This will output to the console: 'Boston🍩'. 36 | -------------------------------------------------------------------------------- /snippets/js-promise-all-28-05-2022.js: -------------------------------------------------------------------------------- 1 | const saladRecipe = new Promise((resolve) => { 2 | setTimeout(() => { 3 | resolve("Caesar Salad🥗"); 4 | }, 1000); 5 | }); 6 | 7 | const spaghettiRecipe = new Promise((resolve) => { 8 | setTimeout(() => { 9 | resolve("Spaghetti🍝"); 10 | }, 2000); 11 | }); 12 | 13 | const calamariRecipe = new Promise((resolve) => { 14 | setTimeout(() => { 15 | resolve("Fried Calamari🦑"); 16 | }, 3000); 17 | }); 18 | 19 | // Now we want to get all our orders at the same time to the table! 20 | const order = async () => { 21 | // Promise.all accepts an array of promises. Let's create it! 22 | const recipes = [saladRecipe, spaghettiRecipe, calamariRecipe]; 23 | // Now we can use Promise.all to wait for all of them to finish, then get the results. 24 | const myFood = await Promise.all(recipes); 25 | 26 | // The result is an array of the results of each promise. We can use it to combine the food altogether! 27 | const myMeal = `Here is your ${myFood[0]} with ${myFood[1]} and ${myFood[2]}. All received at the same time!`; 28 | console.log(myMeal); 29 | }; 30 | 31 | order(); 32 | -------------------------------------------------------------------------------- /snippets/js-promise-async-await-syntactic-sugar-24-05-2022.js: -------------------------------------------------------------------------------- 1 | const spaghettiRecipe = () => 2 | new Promise((resolve) => { 3 | console.log("Cooking...🍽️, the spaghetti will ready in 2 seconds!"); 4 | 5 | const spaghetti = "🍝"; 6 | 7 | setTimeout(() => { 8 | // We will need this value in other Promises. 9 | resolve(spaghetti); 10 | }, 2000); 11 | }); 12 | 13 | // Add the async keyword before your argument. 14 | const cookingTime = async () => { 15 | // The await keyword will capture the resolved value in the variable. 16 | const spaghetti = await spaghettiRecipe(); 17 | 18 | // You can also just await a promise without capturing its resolved value. 19 | await spaghettiRecipe(); 20 | 21 | return spaghetti; 22 | }; 23 | 24 | /** 25 | ⚠️ These are advanced concepts. Might cause confusion if you did not understand the previous posts. ⚠️ 26 | */ 27 | 28 | // Labelling a function as async means that it will return a promise. Afterwards, you can use .then or await it too. 29 | cookingTime().then(console.log); 30 | -------------------------------------------------------------------------------- /snippets/js-promise-async-await-then-03-05-2022.js: -------------------------------------------------------------------------------- 1 | const API_ROUTE = "https://www.nokeynoshade.party/api/queens/all"; 2 | 3 | const getAllQueens = async () => { 4 | const response = await fetch(API_ROUTE); 5 | const queens = await response.json(); 6 | return queens; 7 | }; 8 | 9 | fetch(API_ROUTE) 10 | .then((data) => data.json()) 11 | .then((queens) => { 12 | // Now, you can do anything you want with the data. 13 | console.log(queens[0]); 14 | }); 15 | 16 | // Link to Twitter post: https://twitter.com/TommiEng/status/1521631124656635906 17 | -------------------------------------------------------------------------------- /snippets/js-promise-introduction-20-05-2022.js: -------------------------------------------------------------------------------- 1 | // We can create a promise with the Promise constructor. 2 | const spaghettiRecipe = new Promise((resolve) => { 3 | console.log("Cooking...🍽️, the spaghetti will ready in 2 seconds!"); 4 | 5 | // Here are instructions on how to get the final value: 6 | const spaghetti = "Dinner is ready!🍝"; 7 | 8 | // Any code requiring time can be in a promise: 9 | setTimeout(() => { 10 | // The resolve value is what matters: 11 | resolve(spaghetti); 12 | }, 2000); 13 | }); 14 | 15 | const cookSpaghettiRecipe = async () => { 16 | // Await this function and store the resolved value in a variable: 17 | const result = await spaghettiRecipe; 18 | console.log(result); 19 | }; 20 | 21 | cookSpaghettiRecipe(); 22 | -------------------------------------------------------------------------------- /snippets/js-promise-reject-30-05-2022.js: -------------------------------------------------------------------------------- 1 | // Rejecting a promise can happen for many reasons. For example, if we have a network error, or if we have a problem with the data we are getting from the server. 2 | 3 | // Let's imagine such a scenario: We have an order for dumplings, but we fried them instead of steaming them like the order says. 4 | 5 | // We only have a recipe for fried dumplings. 6 | const dumplingsRecipe = () => 7 | new Promise((resolve) => { 8 | setTimeout(() => { 9 | resolve("Fried dumplings🥟"); 10 | }, 1000); 11 | }); 12 | 13 | // We now receive an order for boiled dumplings: 14 | const steamedDumplingsOrder = () => 15 | new Promise((resolve, reject) => { 16 | // We have to cook our dumplings with our only recipe. 17 | dumplingsRecipe().then((dumplings) => { 18 | // If we cook our dumplings correctly, we can resolve the promise. 19 | if (dumplings === "Steamed dumplings🥟") { 20 | resolve(dumplings); 21 | // If we cook our dumplings incorrectly, we can reject the promise. 22 | } else { 23 | reject("❌ This is not the dumplings I ordered."); 24 | } 25 | }); 26 | }); 27 | 28 | steamedDumplingsOrder().catch(console.error); 29 | 30 | // Twitter reference: https://twitter.com/TommiEng/status/1531331593704554496 31 | -------------------------------------------------------------------------------- /snippets/js-promise-setTimeout-11-04-2022.js: -------------------------------------------------------------------------------- 1 | async function delay (seconds) { 2 | return new Promise( resolve => { 3 | setTimeout(resolve, seconds * 1000); 4 | }); 5 | } 6 | 7 | async function mainScript() { 8 | console.log("Doing something"); 9 | await delay(1); 10 | console.log("Doing something else"); 11 | await delay(2); 12 | console.log("Doing another thing"); 13 | await delay(3); 14 | console.log("Finished!"); 15 | } 16 | 17 | mainScript(); -------------------------------------------------------------------------------- /snippets/js-promise-then-chaining-23-05-2022.js: -------------------------------------------------------------------------------- 1 | // same Promise as fridays post. 2 | const spaghettiRecipe = new Promise((resolve) => { 3 | console.log("Cooking...🍽️, the spaghetti will ready in 2 seconds!"); 4 | 5 | const spaghetti = "Dinner is ready!🍝"; 6 | setTimeout(() => { 7 | // We will need this value in other promises. 8 | resolve(spaghetti); 9 | }, 2000); 10 | }); 11 | 12 | const cookSpaghettiRecipe = () => { 13 | // Simply typing the promise will kick it off, but that won't do much: 14 | spaghettiRecipe; 15 | 16 | // We need to capture the resolved value. We can do this with the .then method on our promise object. The .then accepts a function: 17 | 18 | spaghettiRecipe 19 | // This function received the promise's resolved value as its argument! 20 | .then((resolvedValue) => { 21 | console.log("Resolved value of first promise: ", resolvedValue); 22 | // This will resolve as: 'Dinner is ready!🍝' 'Dinner is ready!🍝' 23 | return resolvedValue.repeat(2); 24 | }) 25 | // You can chain .then endlessly, as .then itself returns a promise. Kinda like the movie Inception! 26 | 27 | // The return value of the previous .then function will be the resolved value of this new promise. 28 | .then((resolvedValue2) => { 29 | console.log("Resolved value of second promise: ", resolvedValue2); 30 | }); 31 | }; 32 | 33 | cookSpaghettiRecipe(); 34 | -------------------------------------------------------------------------------- /snippets/js-recursive-factorial-14-04-2022.js: -------------------------------------------------------------------------------- 1 | // If the number provided is not 1, the factorial function will call itself! 2 | 3 | const factorial = (number) => { 4 | if (number === 1) { 5 | return number; 6 | } 7 | 8 | return number * factorial(number - 1); 9 | } 10 | 11 | factorial(1); 12 | // This call returns 1. 13 | 14 | factorial(4); 15 | // This would return 4 * 3 * 2 * 1, which equals to 24. -------------------------------------------------------------------------------- /snippets/js-remove-duplicates-array-05-04-2022.js: -------------------------------------------------------------------------------- 1 | const countries = [ 2 | "United States", 3 | "Canada", 4 | "Nigeria", 5 | "India", 6 | "Vietnam", 7 | "Vietnam", 8 | "United Kingdom", 9 | ]; 10 | 11 | const countriesSet = Set(countries); 12 | // countriesSet's value would be: {"United States", "Canada", "Nigeria", "India", "Vietnam", "United Kingdom"}; 13 | 14 | const countriesArray = [...countriesSet]; 15 | // Spread the countriesSet object to put it back into an array form. 16 | 17 | console.log(countriesArray); 18 | // ["United States", "Canada", "Nigeria", "India", "Vietnam", "United Kingdom"]; 19 | -------------------------------------------------------------------------------- /snippets/js-rest-parameters-07-10-2022.js: -------------------------------------------------------------------------------- 1 | const teach = (sport, language, ...subjects) => { 2 | console.log("Sport:", sport); 3 | console.log("Language:", language); 4 | console.log("Other subjects:", subjects); 5 | }; 6 | 7 | teach("Swimming", "JavaScript", "Algebra", "English", "CSS"); 8 | /* 9 | Sport: "Swimming" 10 | Language: "JavaScript" 11 | Other subjects: ["Algebra", "English", "CSS"] 12 | */ 13 | 14 | // Despite that we're just giving one value for the rest parameter, it still becomes an array: 15 | teach("Boxing", "French", "UX Design"); 16 | /* 17 | Sport: "Boxing" 18 | Language: "French" 19 | Other subjects: ["UX Design"] 20 | */ 21 | 22 | // Combining rest parameters with regular parameters: 23 | function filterAdults(limit, ...ages) { 24 | return ages.filter((age) => age >= limit); 25 | } 26 | 27 | const adults = filterAdults(18, 25, 3, 42, 11, 78); 28 | console.log(adults); // [25, 42, 78] 29 | -------------------------------------------------------------------------------- /snippets/js-reverse-string-28-03-2022.js: -------------------------------------------------------------------------------- 1 | const reverse = (string) => { 2 | return [...string].reverse().join(""); 3 | }; 4 | 5 | reverse("Tommie"); 6 | 7 | // Here are the steps: 8 | // 1. [...string] will return: ["T", "o", "m", "m", "i", "e"] 9 | 10 | // 2. [...string].reverse() returns: ["e", "i", "m", "m", "o", "T"] 11 | 12 | // 3. [...string].reverse().join("") returns: "eimmoT" 13 | -------------------------------------------------------------------------------- /snippets/js-set-07-04-2022.js: -------------------------------------------------------------------------------- 1 | // What is a Set? Set objects contains values that can only occur a single time! 2 | // Each of the values are unique, so sets cannot have duplicates! 3 | 4 | // Here’s how would you go to create your first set! 5 | const set = new Set(); 6 | 7 | 8 | // Next, let’s try adding fruits in the set! 9 | set.add('mango'); 10 | set.add('dragon fruit'); 11 | 12 | // Is a certain item in the set? Let’s check it out! 13 | set.has('mango'); // Returns true 14 | set.has('coconut'); // Returns false 15 | 16 | // The dragon fruit is not ripe yet? Time to delete it! 17 | set.delete('dragon fruit'); 18 | 19 | // How many fruits are left in the set? Let’s find out. 20 | set.size(); 21 | 22 | // Nothing like a fresh start. Let’s delete everything! 23 | set.clear(); 24 | -------------------------------------------------------------------------------- /snippets/js-sorting-arrays-23-03-2022.js: -------------------------------------------------------------------------------- 1 | const numbers = [3, 99, 55, 11, 7]; 2 | 3 | numbers.sort(); 4 | // Sorts alphabetically by default when not specifying a function: [11, 3, 55, 7, 99] 5 | 6 | numbers.sort((a, b) => a - b); 7 | // Sorts by ascending order, from smallest to largest numbers: [3, 7, 11, 55, 99] 8 | 9 | numbers.sort((a, b) => b - a); 10 | // Sorts by descending order: [99, 55, 11, 7, 3] 11 | -------------------------------------------------------------------------------- /snippets/js-spread-syntax-04-10-2022.js: -------------------------------------------------------------------------------- 1 | // Use the elements of an array as arguments to a function. 2 | const logMeal = (breakfast, lunch, dinner) => { 3 | console.log(breakfast, lunch, dinner); 4 | }; 5 | 6 | const arguments = ["bagel🥯", "salad🥗", "pad Thai🥡"]; 7 | logMeal(...arguments); 8 | 9 | // Spread syntax in arrays: 10 | const missingParts = ["get", "bitter"]; 11 | const quote = ["don't", ...missingParts, "just", "get", "better"]; 12 | // ["don't", "get", "bitter", "just", "get", "better"] 13 | 14 | // Cloning an array: 15 | const fruitsArray = ["banana🍌", "cherry🍒", "pear🍐"]; 16 | const fruitsArrayCopy = [...fruitsArray]; 17 | 18 | // Concatenate arrays: 19 | const veggies1 = ["mushroom🍄", "cucumber🥒"]; 20 | const veggies2 = ["onion🧅", "garlic🧄"]; 21 | 22 | const veggies = [...veggies1, ...veggies2]; 23 | // ["mushroom🍄", "cucumber🥒", "onion🧅", "garlic🧄"] 24 | 25 | // Spread syntax in objects 26 | const tea = { type: "Green" }; 27 | const cat = { name: "Garfield", breed: "Tabby Persian cat" }; 28 | 29 | const clonedObject = { ...cat }; 30 | // Object { name: "Garfield", breed: "Tabby Persian cat" } 31 | 32 | const newObject = { ...tea, ...cat }; 33 | // Object { type: "Green", name: "Garfield", breed: "Tabby Persian cat" } 34 | -------------------------------------------------------------------------------- /snippets/js-static-OOP-09-05-2022.js: -------------------------------------------------------------------------------- 1 | // Mock data from a Garden API 2 | const vegetables = { 3 | "tomato🍅": 5, 4 | "potato🥔": 10, 5 | }; 6 | 7 | // Static methods are a good way to wrap a REST API and encapsulate it. Here, we are mocking a subset of REST methods around a Garden API. 8 | class GardenAPI { 9 | static getAllVeggies = () => { 10 | return vegetables; 11 | }; 12 | 13 | static eatVeggie = (veggie) => { 14 | vegetables[veggie] = vegetables[veggie] - 1; 15 | }; 16 | 17 | static water = () => { 18 | for (const veggie of Object.keys(vegetables)) { 19 | vegetables[veggie] = vegetables[veggie] + 1; 20 | } 21 | }; 22 | } 23 | 24 | // Get all the veggies! 25 | console.log("We start with these veggies: ", GardenAPI.getAllVeggies()); 26 | 27 | // Eat one and see how many are left! 28 | GardenAPI.eatVeggie("potato🥔"); 29 | console.log("What's left to eat: ", GardenAPI.getAllVeggies()); 30 | 31 | // Let's water the veggies plants! 32 | GardenAPI.water(); 33 | console.log("Watering the following veggies: ", GardenAPI.getAllVeggies()); 34 | 35 | // Static methods have other uses as well (which, we'll explore more later on)! 36 | -------------------------------------------------------------------------------- /snippets/js-string-method-split-17-05-2022.js: -------------------------------------------------------------------------------- 1 | const trivia = 2 | "Taiwan's the first country in Asia to accept same-sex marriage."; 3 | trivia.split(" "); 4 | // This will return: ["Taiwan's", 'the', 'first', 'country', 'in', 'Asia', 'to', 'accept', 'same-sex', 'marriage.'] 5 | 6 | const violations = "Homophobia🏳️‍🌈,Transphobia🏳️‍⚧️,Biphobia"; 7 | violations.split(","); 8 | // This would return: ['Homophobia🏳️‍🌈', 'Transphobia🏳️‍⚧️', 'Biphobia'] 9 | -------------------------------------------------------------------------------- /snippets/js-template-literals-02-05-2022.js: -------------------------------------------------------------------------------- 1 | const introduction = (name, job) => { 2 | const sentence = `Hello, my name is ${firstName} and I'm a ${job}`; 3 | return sentence; 4 | }; 5 | 6 | console.log(introduction("Tommie", "Software Engineer🧑‍💻")); 7 | // This outputs: "Hello, my name is Tommie and I'm a Software Engineer🧑‍💻" 8 | 9 | console.log(`I could 10 | really go for some 11 | Pad thai right now.🥢`); 12 | // This outputs: 13 | // "I could 14 | // really go for some 15 | // Pad thai right now.🥢" 16 | -------------------------------------------------------------------------------- /snippets/js-ternary-04-04-2022.js: -------------------------------------------------------------------------------- 1 | const banana = "yellow"; 2 | 3 | banana === "yellow" 4 | ? console.log(`It's ripe!`) 5 | : console.log(`It's not ripe yet!`); 6 | // Condition ? If : Else 7 | 8 | const bark = (sound) => { 9 | return sound === "Woof" ? "It's a dog!" : "It's not a dog."; 10 | }; 11 | 12 | console.log(bark("Woof")); 13 | // This outputs to the console: "It's a dog!" 14 | 15 | console.log(bark("Meow")); 16 | // This outputs to the console: "It's not a dog." 17 | -------------------------------------------------------------------------------- /snippets/js-the-date-constructor-24-02-2022.js: -------------------------------------------------------------------------------- 1 | // JavaScript date constructor, returns today's date 2 | const today = new Date(); 3 | 4 | console.log(today.getDay()); 5 | // Today's day 6 | 7 | console.log(today.getMonth()); 8 | // Today's month, the month ranging from 0 - 11 9 | 10 | console.log(today.getFullYear()); 11 | // Today's year, which would be 2022 12 | -------------------------------------------------------------------------------- /snippets/js-try-catch-12-04-2022.js: -------------------------------------------------------------------------------- 1 | try { 2 | // Since this function does not exist, it will throw an error. 3 | notDefinedFunction(); 4 | 5 | // You can also do manuel checks and throw Errors! 6 | if (!process.env.VAR) { 7 | throw new Error("VAR is not defined"); 8 | } 9 | } 10 | // Catch will get the first error to occur in the try above. 11 | catch (error) { 12 | console.error(error); 13 | } -------------------------------------------------------------------------------- /snippets/js-typeof-operator-15-03-2022.js: -------------------------------------------------------------------------------- 1 | console.log(typeof "LGBTQ+ in Tech"); 2 | // Returns: "string" 3 | 4 | console.log(typeof 1234); 5 | // Returns: "number" 6 | 7 | console.log(typeof false); 8 | // Returns: "boolean" 9 | 10 | if (typeof variable == "undefined") { 11 | // Catch the error... 12 | } 13 | 14 | // Other types include null, undefined, function. 15 | -------------------------------------------------------------------------------- /snippets/react-accessing-the-dom-13-09-2022.jsx: -------------------------------------------------------------------------------- 1 | // ⚠️ This snippet won't run, as I'm using a fictional UI library as an example! ⚠️ 2 | 3 | import React, { useEffect, useRef } from "react"; 4 | // This imported library doesn't exist. 🙅‍♀️ It's just here for the sake of the example! 5 | import UILibraryElement from "ui-library-element"; 6 | 7 | const Component = ({ children }) => { 8 | // Creating a ref with the useRef() hook. 🪝 9 | const uiLibraryRef = useRef(); 10 | 11 | useEffect(() => { 12 | // Add a useEffect callback here and using an UI library element to make it look cute. 💄 13 | const node = uiLibraryRef.current; 14 | UILibraryElement.initialize(node); 15 | 16 | // Don't forget to return a cleanup function for when the component is unmounted. 🧹 17 | // If not, we'll have event handlers polluting DOM nodes that aren't in the document anymore. 18 | return () => node.uiLibraryRef.destroy(); 19 | 20 | // Remember to specify your effect's dependencies array! We know that our node will never change, so make it an empty array. 21 | }, []); 22 | 23 | // Adding the ref prop to the div. 👇 24 | return ( 25 |
    26 |
    {children}
    27 |
    28 | ); 29 | }; 30 | 31 | const App = () => { 32 | return ( 33 | 34 |
    UI Library Element
    35 |
    36 | ); 37 | }; 38 | 39 | export default App; 40 | -------------------------------------------------------------------------------- /snippets/react-api-intro-15-06-2022.html: -------------------------------------------------------------------------------- 1 | 2 |
    3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 25 | -------------------------------------------------------------------------------- /snippets/react-colocating-state-06-09-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | 3 | const StudentName = ({ name, onNameChange }) => { 4 | return ( 5 |
    6 | 7 | 13 |
    14 | ); 15 | }; 16 | 17 | // Notice how the studentNumber state could've been in App, but it is currently 18 | // in the StudentNumber component, where it's more relevant! 19 | const StudentNumber = () => { 20 | const [studentNumber, setStudentNumber] = useState(""); 21 | 22 | return ( 23 |
    24 | 25 | setStudentNumber(event.target.value)} 29 | placeholder="12345" 30 | /> 31 |
    32 | ); 33 | }; 34 | 35 | const Greeting = ({ name }) => { 36 | return
    {`Welcome back to school ${name} 🎒`}
    ; 37 | }; 38 | 39 | const App = () => { 40 | const [name, setName] = useState(""); 41 | 42 | return ( 43 |
    44 | setName(event.target.value)} 47 | /> 48 | 49 | 50 | 51 | ); 52 | }; 53 | 54 | export default App; 55 | -------------------------------------------------------------------------------- /snippets/react-custom-jsx-component-23-06-2022.html: -------------------------------------------------------------------------------- 1 | 2 |
    3 | 4 | 5 | 6 | 7 | 24 | -------------------------------------------------------------------------------- /snippets/react-custom-styling-12-07-2022.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "../css-planet-styles.css"; 3 | 4 | const Planet = ({ style, planet, className = "", children }) => { 5 | const planetClassName = planet ? `planet--${planet}` : ""; 6 | 7 | return ( 8 |
    12 | {children} 13 |
    14 | ); 15 | }; 16 | 17 | const SolarSystemApp = () => { 18 | return ( 19 |
    20 | 21 | Mars 22 | 23 | 27 | Earth 28 | 29 | Unknown 30 |
    31 | ); 32 | }; 33 | 34 | export default SolarSystemApp; 35 | -------------------------------------------------------------------------------- /snippets/react-error-boundary-30-09-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import { ErrorBoundary } from "react-error-boundary"; 3 | 4 | const ErrorFallback = ({ error }) => { 5 | return ( 6 |
    7 |

    ⚠️ Something went wrong with the coffee machine:

    8 |
    {error.message}
    9 |
    10 | ); 11 | }; 12 | 13 | const CoffeeMachine = () => { 14 | throw new Error("Coffee machine is out of order. ⛔"); 15 | }; 16 | 17 | const App = () => { 18 | const [brew, setBrew] = useState(false); 19 | const handleClick = () => setBrew(true); 20 | 21 | return ( 22 |
    23 | 24 | 25 | {brew ? : null} 26 | 27 |
    28 | ); 29 | }; 30 | 31 | export default App; 32 | -------------------------------------------------------------------------------- /snippets/react-form-intro-14-07-2022.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const PronounsForm = (props) => { 4 | 5 | const handleSubmit = (event) => { 6 | /* 7 | This prevents form submit events' default behaviour (page refresh). 8 | Read more here: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault 9 | */ 10 | event.preventDefault(); 11 | const pronouns = event.target.elements[0].value; 12 | props.onSubmitPronouns(pronouns); 13 | } 14 | 15 | return ( 16 |
    17 |
    18 | {/* The htmlFor prop associates the label to its input. */} 19 | 20 | 21 |
    22 | 23 |
    24 | ); 25 | } 26 | 27 | const PronounsApp = () => { 28 | const onSubmitPronouns = pronouns => alert(`Your pronouns are: ${pronouns} 🏳️‍🌈`); 29 | return ; 30 | } 31 | 32 | export default PronounsApp; -------------------------------------------------------------------------------- /snippets/react-form-useRef-19-07-2022.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const IceCreamForm = (props) => { 4 | const iceCreamInputRef = React.useRef(); 5 | 6 | const handleSubmit = (event) => { 7 | event.preventDefault(); 8 | props.onSubmitIceCream(iceCreamInputRef.current.value); 9 | } 10 | 11 | return ( 12 |
    13 |
    14 | 15 | 16 |
    17 | 18 |
    19 | ); 20 | } 21 | 22 | const IceCreamApp = () => { 23 | const onSubmitIceCream = iceCream => alert(`You ordered: ${iceCream} ice cream`); 24 | return ; 25 | } 26 | 27 | export default IceCreamApp; -------------------------------------------------------------------------------- /snippets/react-fragment-01-07-2022.html: -------------------------------------------------------------------------------- 1 | 2 |
    3 | 4 | 5 | 6 | 7 | 8 | 33 | -------------------------------------------------------------------------------- /snippets/react-http-request-15-09-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from "react"; 2 | import { DragRaceWinners } from "../components/DragRaceWinners"; 3 | 4 | const App = () => { 5 | const [winners, setWinners] = useState(); 6 | 7 | useEffect(() => { 8 | fetch("http://www.nokeynoshade.party/api/queens/winners") 9 | .then((response) => response.JSON()) 10 | .then((data) => setWinners(data)); 11 | }, []); 12 | 13 | return ; 14 | }; 15 | 16 | export default App; 17 | -------------------------------------------------------------------------------- /snippets/react-http-requests-handling-errors.20-09-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from "react"; 2 | import { DragRaceWinners } from "../components/DragRaceWinners"; 3 | 4 | const App = () => { 5 | const [winners, setWinners] = useState(null); 6 | const [error, setError] = useState(null); 7 | 8 | useEffect(() => { 9 | fetch("http://www.nokeynoshade.party/api/queens/winners") 10 | .then( 11 | (response) => response.json(), 12 | (error) => setError(error) 13 | ) 14 | .then((data) => setWinners(data)); 15 | }, []); 16 | 17 | if (error) { 18 | return ( 19 |
    20 | ⚠️ Uh oh, an error occured:
    {error.message}
    21 |
    22 | ); 23 | } else { 24 | return ; 25 | } 26 | }; 27 | 28 | export default App; 29 | -------------------------------------------------------------------------------- /snippets/react-http-requests-state-object-27-09-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | import { DragRaceWinners } from "../components/DragRaceWinners"; 3 | 4 | const App = () => { 5 | const [state, setState] = useState({ 6 | status: "idle", 7 | winners: null, 8 | }); 9 | 10 | const { status, winners } = state; 11 | 12 | useEffect(() => { 13 | setState({ status: "pending" }); 14 | 15 | fetch("http://www.nokeynoshade.party/api/queens/winners") 16 | .then((response) => { 17 | response.json(); 18 | setState({ status: "resolved", winners: response }); 19 | }) 20 | .then((data) => setState(data)); 21 | }, []); 22 | 23 | if (status === "idle") { 24 | return "No HTTP request yet. 🤷"; 25 | } else if (status === "pending") { 26 | return "Loading...⏳"; 27 | } else if (status === "resolved") { 28 | return ; 29 | } 30 | 31 | throw new Error("This line should be unreachable."); 32 | }; 33 | 34 | export default App; 35 | -------------------------------------------------------------------------------- /snippets/react-http-requests-status-22-09-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | import { DragRaceWinners } from "../components/DragRaceWinners"; 3 | 4 | const App = () => { 5 | const [status, setStatus] = useState("idle"); 6 | const [winners, setWinners] = useState(null); 7 | const [error, setError] = useState(null); 8 | 9 | useEffect(() => { 10 | setStatus("pending"); 11 | fetch("http://www.nokeynoshade.party/api/queens/winners") 12 | .then( 13 | (response) => { 14 | response.json(); 15 | setStatus("resolved"); 16 | }, 17 | (error) => { 18 | setError(error); 19 | setStatus("rejected"); 20 | } 21 | ) 22 | .then((data) => setWinners(data)); 23 | }, []); 24 | 25 | if (status === "idle") { 26 | return "No HTTP request yet. 🤷"; 27 | } else if (status === "pending") { 28 | return "Loading...⏳"; 29 | } else if (status === "rejected") { 30 | return ( 31 |
    32 | ⚠️ Uh oh, an error occured:
    {error.message}
    {" "} 33 |
    34 | ); 35 | } else if (status === "resolved") { 36 | return ; 37 | } 38 | 39 | throw new Error("This line should be unreachable."); 40 | }; 41 | 42 | export default App; 43 | -------------------------------------------------------------------------------- /snippets/react-introduction-to-useEffect-09-08-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | 3 | const Library = ({ defaultBook = "" }) => { 4 | // Start by seeing if the book value exists in our localStorage: 5 | const [book, setBook] = useState(localStorage.getItem("book") ?? defaultBook); 6 | 7 | // Let's set the name in our localStorage with useEffect: 8 | useEffect(() => { 9 | localStorage.setItem("book", book); 10 | }); 11 | 12 | const handleChange = (event) => { 13 | setBook(event.target.value); 14 | }; 15 | 16 | return ( 17 |
    18 |
    19 | 20 | 21 |
    22 | {book ? ( 23 | I'd like to borrow {book}, please. 24 | ) : ( 25 | "Which book(s) would you like to borrow? 📚" 26 | )} 27 |
    28 | ); 29 | }; 30 | 31 | export const App = () => { 32 | return ; 33 | }; 34 | -------------------------------------------------------------------------------- /snippets/react-key-prop-21-07-2022.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const PieApp = () => { 4 | const pies = [ 5 | { id: "peach", value: "peach 🍑" }, 6 | { id: "cherry", value: "cherry 🍒" }, 7 | { id: "blueberry", value: "blueberry 🫐" }, 8 | { id: "mango", value: "mango 🥭" }, 9 | ]; 10 | 11 | return ( 12 |
    13 |

    Behold a list of delicious pie flavours:

    14 | 15 |
      16 | {pies.map((pie) => ( 17 |
    • 18 | {pie.value} 19 |
    • 20 | ))} 21 |
    22 |
    23 | ); 24 | }; 25 | 26 | export default PieApp; 27 | -------------------------------------------------------------------------------- /snippets/react-lazy-initial-state-11-08-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | 3 | const Library = ({ defaultBook = "" }) => { 4 | // Use lazy initial state to prevent reading from localStorage on each render: 5 | const [book, setBook] = React.useState( 6 | () => window.localStorage.getItem("book") ?? defaultBook 7 | ); 8 | 9 | useEffect(() => { 10 | localStorage.setItem("book", book); 11 | }); 12 | 13 | const handleChange = (event) => { 14 | setBook(event.target.value); 15 | }; 16 | 17 | return ( 18 |
    19 |
    20 | 21 | 22 |
    23 | {book ? ( 24 | I'd like to borrow {book}, please. 25 | ) : ( 26 | "Which book(s) would you like to borrow? 📚" 27 | )} 28 |
    29 | ); 30 | }; 31 | 32 | export const App = () => { 33 | return ; 34 | }; 35 | -------------------------------------------------------------------------------- /snippets/react-lifting-state-up-23-08-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | 3 | const Taco = ({ taco, onTacoChange }) => { 4 | return ( 5 |
    6 | 7 | 13 |
    14 | ); 15 | }; 16 | 17 | const Bebida = ({ bebida, onBebidaChange }) => { 18 | return ( 19 |
    20 | 21 | 27 |
    28 | ); 29 | }; 30 | 31 | const Order = ({ taco, bebida }) => { 32 | return ( 33 |
    {`Me gustaría un(a) ${taco} taco y beber un(a) ${bebida} por favor. 🌮`}
    34 | ); 35 | }; 36 | 37 | const App = () => { 38 | const [taco, setTaco] = useState(""); 39 | const [bebida, setBebida] = useState(""); 40 | 41 | return ( 42 |
    43 | setTaco(event.target.value)} /> 44 | setBebida(event.target.value)} 47 | /> 48 | 49 | 50 | ); 51 | }; 52 | 53 | export default App; 54 | -------------------------------------------------------------------------------- /snippets/react-propTypes-28-05-2022.html: -------------------------------------------------------------------------------- 1 | 2 |
    3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 33 | -------------------------------------------------------------------------------- /snippets/react-spreading-props-21-06-2022.html: -------------------------------------------------------------------------------- 1 | 2 |
    3 | 4 | 5 | 6 | 7 | 8 | 21 | -------------------------------------------------------------------------------- /snippets/react-styling-07-07-2022.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const mars = ( 4 |
    8 | Planet Mars 9 |
    10 | ); 11 | 12 | const earth = ( 13 |
    14 | Planet Earth 15 |
    16 | ); 17 | 18 | const css = ` 19 | .planet { 20 | display: flex; 21 | flex-direction: column; 22 | justify-content: center; 23 | text-align: center; 24 | border-radius: 50%; 25 | } 26 | 27 | .planet--earth { 28 | width: 200px; 29 | height: 200px; 30 | color: white; 31 | } 32 | 33 | .planet--mars { 34 | width: 100px; 35 | height: 100px; 36 | } 37 | `; 38 | 39 | function App() { 40 | return ( 41 | <> 42 | 43 | {mars} 44 | {earth} 45 | 46 | ); 47 | } 48 | 49 | export default App; 50 | -------------------------------------------------------------------------------- /snippets/react-styling-with-css-modules-25-08-2022.jsx: -------------------------------------------------------------------------------- 1 | // Suppose we have two files: our styles.module.css file and our JSX file. 2 | 3 | // styles.module.css 4 | 5 | // .hosting { 6 | // font: 2rem Helvetica, Arial, sans-serif; 7 | // color: white; 8 | // background: hsl(268, 29%, 48%); 9 | // padding: 100px; 10 | // text-align: center; 11 | // transition: 100ms ease-in background; 12 | // } 13 | 14 | // .hosting:hover { 15 | // background: black; 16 | // } 17 | 18 | /* 19 | ------------------------------------------------------- 20 | */ 21 | 22 | // import styles from "../styles.module.css"; 23 | 24 | const Hosting = () => { 25 | return ( 26 |
    27 | Farewell Heroku. Hello Vercel. 28 |
    29 | ); 30 | }; 31 | 32 | export default Hosting; 33 | -------------------------------------------------------------------------------- /snippets/react-use-effect-dependency-array-16-08-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | 3 | const TellAJoke = ({ 4 | defaultJoke = "What did the big flower say to the littler flower? Hi, bud! 🌼", 5 | }) => { 6 | const [joke, setJoke] = useState( 7 | () => localStorage.getItem("joke") ?? defaultJoke 8 | ); 9 | 10 | useEffect(() => { 11 | localStorage.setItem("joke", joke); 12 | }, [joke]); 13 | 14 | const handleChange = (event) => { 15 | setJoke(event.target.value); 16 | }; 17 | 18 | return ( 19 |
    20 |
    21 | 22 | 23 |
    24 | {joke ? {joke} : "Please tell me a joke. 🤡"} 25 |
    26 | ); 27 | }; 28 | 29 | const App = () => { 30 | return ; 31 | }; 32 | 33 | export default App; 34 | -------------------------------------------------------------------------------- /snippets/react-useReducer-basics-20-10-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, {useReducer} from "react"; 2 | 3 | const gelatoReducer = (amount, change) => amount + change; 4 | 5 | const Gelato = ({initialAmount = 10, step = 2}) => { 6 | 7 | const [numberOfGelato, setNumberOfGelato] = useReducer(gelatoReducer, initialAmount); 8 | 9 | const addGelato = () => setNumberOfGelato(step); 10 | 11 | return ; 12 | } 13 | 14 | const App = () => { 15 | return ; 16 | } 17 | 18 | export default App; -------------------------------------------------------------------------------- /snippets/react-useReducer-setState-object-28-10-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, {useReducer} from "react" 2 | 3 | const gelatoReducer = (state, action) => ({...state, ...action}); 4 | 5 | const Gelato = ({initialAmount = 0, change = 1}) => { 6 | 7 | const [state, setState] = useReducer(gelatoReducer, {amount: initialAmount}); 8 | const {amount} = state; 9 | const addGelato = () => setState({amount: amount + change}); 10 | 11 | return ; 12 | } 13 | 14 | const App = () => { 15 | return ; 16 | } 17 | 18 | export default App; -------------------------------------------------------------------------------- /snippets/react-useState-28-07-2022.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const Internship = () => { 4 | const [company, setCompany] = React.useState(""); 5 | 6 | const handleChange = (event) => { 7 | setCompany(event.target.value); 8 | }; 9 | 10 | return ( 11 |
    12 |
    13 | 14 | 15 |
    16 | {company ? ( 17 | You would like to be an intern at {company}. 18 | ) : ( 19 | "Please type the company where you'd like to be an intern." 20 | )} 21 |
    22 | ); 23 | }; 24 | 25 | const App = () => { 26 | return ; 27 | }; 28 | 29 | export default App; 30 | -------------------------------------------------------------------------------- /snippets/react-useState-initialProp-04-08-2022.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | // If no initialState is passed as a prop, it defaults to false. 4 | const Toggle = ({ initialState = false }) => { 5 | // Pass that initialState as an argument to the useState hook. 6 | const [on, setOn] = React.useState(initialState); 7 | 8 | const handleClick = () => { 9 | setOn(!on); 10 | }; 11 | 12 | return ; 13 | }; 14 | 15 | const App = () => { 16 | // Pass the initialState prop to the Toggle component. 17 | return ; 18 | }; 19 | 20 | export default App; 21 | -------------------------------------------------------------------------------- /snippets/react-useState-timer-02-08-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | 3 | const Timer = () => { 4 | const [seconds, setSeconds] = useState(0); 5 | const add = () => setSeconds(seconds + 1); 6 | 7 | return ; 8 | }; 9 | 10 | const App = () => { 11 | return ; 12 | }; 13 | 14 | export default App; 15 | -------------------------------------------------------------------------------- /snippets/react-useStateWithLocalStorage-custom-hook-18-08-2022.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | 3 | // Reusable custom hook that looks for a key in localStorage if the key exists and updates its value. 4 | const useStateWithLocalStorage = (key, defaultValue = "") => { 5 | const [state, setState] = useState( 6 | () => localStorage.getItem(key) ?? defaultValue 7 | ); 8 | 9 | useEffect(() => { 10 | localStorage.setItem(key, state); 11 | }, [key, state]); 12 | return [state, setState]; 13 | }; 14 | 15 | const Birthday = ({ initialGuestOfHonor = "Guillaume" }) => { 16 | const [guest, setGuest] = useStateWithLocalStorage( 17 | "guestOfHonor", 18 | initialGuestOfHonor 19 | ); 20 | 21 | const handleChange = (event) => { 22 | setGuest(event.target.value); 23 | }; 24 | 25 | return ( 26 |
    27 |
    28 | 29 | 30 |
    31 | {guest ? ( 32 | Happy birthday, {guest} 🎂 33 | ) : ( 34 | "Whose birthday is it today?" 35 | )} 36 |
    37 | ); 38 | }; 39 | 40 | const App = () => { 41 | return ; 42 | }; 43 | export default App; 44 | -------------------------------------------------------------------------------- /snippets/ts-built-in-types-and-primitives.ts: -------------------------------------------------------------------------------- 1 | /* 2 | If you hover over variable a, you should be able to see the type inference. 3 | Once you remove the assignment, TypeScript will not have enough info to infer anymore. 4 | */ 5 | let a = 7; 6 | 7 | // Here's examples of how to explicitly define a variable's type: 8 | let name: string; 9 | let age: number; 10 | let isHungry: boolean; 11 | let date: Date; 12 | let pets: string[]; 13 | 14 | /* 15 | If you try to assign one of the variables to a wrong type, TS will show you errors. 16 | Try to fix this if you can! 17 | */ 18 | pets = 12345; 19 | 20 | /* 21 | Did you intentionally want to assign a different type to your variable? 22 | This is where the any type comes in! 23 | */ 24 | let animals: any; 25 | animals = ["dog🐶", "monkey🐵" ,"whale🐳"]; 26 | animals = 6789; 27 | 28 | /* 29 | Rather than defining holiday as any, I can cast the number value I want to the any type instead. 30 | */ 31 | 32 | let holiday: number; 33 | holiday = "Día de los Muertos" as any; -------------------------------------------------------------------------------- /snippets/ts-custom-types-using-type-aliases-08-11-2022.ts: -------------------------------------------------------------------------------- 1 | /* 2 | To define a type alias, write the type keyword, 3 | followed by the name of the alias of your choice (which would be PiConstant in the example), 4 | followed by an equal sign, and the type that you want to alias. 5 | */ 6 | 7 | interface Pie { 8 | cookedOn: Date; 9 | emoji: string; 10 | flavour: string; 11 | pi: PiConstant; 12 | } 13 | 14 | /* 15 | After defining your first type alias, you can define it any place where you’d use that original type. 16 | For example, we can refactor the Pie interface, changing the type of the pi field from number to PiConstant. 17 | */ 18 | let applePie: Pie = { 19 | cookedOn: new Date("08-11-2022"), 20 | emoji: "🥧", 21 | flavour: "Apple🍎", 22 | pi: 3.14159, 23 | }; 24 | 25 | /* 26 | Also, if we wanted to change all of the PiConstant references, 27 | we could simply change the type that the PiConstant is referring to. 28 | */ 29 | type PiConstant = number; 30 | -------------------------------------------------------------------------------- /snippets/ts-custom-types-with-interfaces-03-11-2022.ts: -------------------------------------------------------------------------------- 1 | // An interface with a property that is optional, and with the Address interface merged into it. 2 | interface Friend extends Address { 3 | name: string; 4 | age?: number; 5 | birthday: Date; 6 | } 7 | 8 | // Another interface that can be used anywhere else in the application. 9 | interface Address { 10 | line: string; 11 | region: string; 12 | country: string; 13 | postalCode: string; 14 | } 15 | 16 | /* 17 | Feel free to play the content of the variable and: 18 | - Test the autocomplete feature of TypeScript. 19 | - Assign one of the fields in the object a wrong type. 20 | - Remove the optional field from the object. 21 | */ 22 | let rupaul: Friend = { 23 | name: "RuPaul", 24 | age: 61, 25 | birthday: new Date("17-11-1960"), 26 | line: "123 Dragstreet", 27 | region: "California", 28 | country: "United States of America", 29 | postalCode: "12345", 30 | }; 31 | -------------------------------------------------------------------------------- /snippets/ts-enum-types-17-11-2022.ts: -------------------------------------------------------------------------------- 1 | interface Friend { 2 | name: string; 3 | age: number; 4 | gender: string; 5 | onlineStatus: OnlineStatus; 6 | } 7 | 8 | enum OnlineStatus { 9 | Online, 10 | Offline, 11 | Away, 12 | } 13 | 14 | let morgan: Friend = { 15 | name: "Morgan", 16 | age: 30, 17 | gender: "Non-binary", 18 | onlineStatus: OnlineStatus.Online, 19 | }; 20 | -------------------------------------------------------------------------------- /snippets/ts-function-arguments-04-05-2022.ts: -------------------------------------------------------------------------------- 1 | function movieReview( 2 | // Indicates title should be a string 3 | title: string, 4 | // Indicates year should be a number 5 | year: number, 6 | 7 | // Forces it to be either 'Good👍' or 'Bad👎' or 'Meh🤷🏽‍♀️' 8 | rating: 'Good👍' | 'Bad👎' | 'Meh🤷🏽‍♀️' 9 | ) { 10 | return `${title} that came out in ${year} was rated ${rating}.`; 11 | } 12 | 13 | 14 | movieReview('Star Wars', 1981, "Average"); 15 | // 🚫 This will not be accepted since the last type is not good. 16 | 17 | movieReview( 'Star Wars',1987, 'Good👍') 18 | // ✅ This returns: `Star Wars that came out in 1987 was rated Good👍.` -------------------------------------------------------------------------------- /snippets/ts-generics-11-05-2022.ts: -------------------------------------------------------------------------------- 1 | type Joke = { 2 | question: string; 3 | punchline: string; 4 | } 5 | 6 | const JOKE_API_URL = 'https://backend-omega-seven.vercel.app/api/getjoke'; 7 | 8 | // As we declare the function, we don't know yet the return type. 9 | async function apiRequest(url: string): Promise { 10 | const res = await window.fetch(url); 11 | const data = res.json(); 12 | 13 | return data; 14 | } 15 | 16 | // When calling the function, we can pass our return type. 17 | apiRequest(JOKE_API_URL) 18 | // Jokes are now typed. 19 | .then(jokes => { /* Do something with the jokes. */ }); -------------------------------------------------------------------------------- /snippets/ts-generics-constraints-08-12-2022.ts: -------------------------------------------------------------------------------- 1 | interface Recipe { 2 | name: string; 3 | durationInMinutes: number; 4 | } 5 | 6 | // An example of generic constraints used with interfaces 7 | interface VegetarianRecipe { 8 | name: string; 9 | durationInMinutes: number; 10 | isVegan: TypeVegan; 11 | } 12 | 13 | // A function example of generics constraints used in a function. 14 | function duplicate(obj: Type1): Type2 { 15 | return { ...obj }; 16 | } 17 | 18 | const sushi: Recipe = { name: "Sushi", durationInMinutes: 60 }; 19 | const sushiClone = duplicate(sushi); 20 | -------------------------------------------------------------------------------- /snippets/ts-generics-revisited-01-12-2022.ts: -------------------------------------------------------------------------------- 1 | interface Today { 2 | occasion: string; 3 | date: Date; 4 | } 5 | 6 | // A function example using generics for the parameter and a return type. 7 | function clone(obj: Type): Type { 8 | return { ...obj }; 9 | } 10 | 11 | // Explicitly typing the variable. Hover over the function call's name to see the type. 12 | const gamma: Today = { 13 | occasion: "World AIDS Day", 14 | date: new Date("2022-12-01"), 15 | }; 16 | const delta = clone(gamma); 17 | 18 | // Not explicitly typing the variable. Hover over the function call's name to see the type. 19 | const virus = { name: "AIDS🦠", isDangerous: true }; 20 | const virusCopy = clone(virus); 21 | 22 | // A function example with a generic typed parameter and a typed return type. 23 | function clone2(obj: Type1): Type2 { 24 | return { ...obj }; 25 | } 26 | 27 | const alpha: Today = { 28 | occasion: "World AIDS Day", 29 | date: new Date("2022-12-01"), 30 | }; 31 | const beta = clone2(alpha); 32 | -------------------------------------------------------------------------------- /snippets/ts-typing-functions-22-11-2022.ts: -------------------------------------------------------------------------------- 1 | // An interface with a typed method in it. 2 | interface Party { 3 | occasion: string; 4 | numOfPeople: number; 5 | date: Date; 6 | clone(example: string): Party; 7 | } 8 | 9 | // A function example with a typed parameter and a return type. 10 | const clone = (obj: Party): Party => { 11 | return { ...obj }; 12 | }; 13 | 14 | // A function example with a function included in the parameters. 15 | const clone2 = (obj: Party, func: (obj: Party) => Party): Party => { 16 | return { ...obj }; 17 | }; 18 | --------------------------------------------------------------------------------