Files
30-seconds-of-code/blog_data/snippets.json
2020-02-27 14:25:32 +00:00

244 lines
34 KiB
JSON

{
"data": [
{
"id": "10-vs-code-extensions-for-js-developers",
"title": "10 must-have VS Code extensions for JavaScript developers",
"type": "blog.list",
"attributes": {
"fileName": "10-vs-code-extensions-for-js-developers.md",
"cover": "blog_images/10-vs-code-extensions-for-js-developers.jpg",
"excerpt": "VS Code is steadily gaining popularity among developers. Here are 10 essential extensions for JavaScript developers that aim to increase your productivity.",
"authors": [
"chalarangelo"
],
"text": "Developers will most likely argue for the rest of eternity about the most productive code editor and the best extensions. Here are my personal extension preferences for VS Code as a JavaScript developer:\n\n1. ESLint\n[ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) turns the popular JavaScrpt linter into an extension of VS Code. It automatically reads your linting configuration, identifies problems and even fixes them for you, if you want.\n\n2. GitLens\n[GitLens](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens) is a very powerful collaboration tool for VS Code. It provides many useful tools for git such as blame, code authorship, activity heatmaps, recent changes, file history and even commit search.\n \n3. Debugger for Chrome\n[Debugger for Chrome](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) allows you to debug your JavaScript code in Chrome or Chromium. Breakpoints, call stack inspection and stepping inside a function are only some of its features.\n\n4. Bracket Pair Colorizer 2\n[Bracket Pair Colorizer 2](https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer-2) makes reading code faster as it makes matching brackets the same color. This extension for VS Code improves upon its predecessor by providing improved performance.\n\n5. Bookmarks\n[Bookmarks](https://marketplace.visualstudio.com/items?itemName=alefragnani.Bookmarks) is one of those extensions that will significantly reduce your time jumping between different files, as it allows you to save important positions and navigate back to them easily and quickly.\n\n6. TODO Highlight\n[TODO Highlight](https://marketplace.visualstudio.com/items?itemName=wayou.vscode-todo-highlight) simplifies tracking leftover tasks by allowing you to list all of your TODO annotations, as well as adding a handy background highlight to them to make them pop out immediately. \n\n7. Live Server\n[Live Server](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) gives you an easy way to serve web pages from VS Code, making previewing and debugging a lot easier. One of the core features is the live reload support that many developers are used to.\n\n8. REST Client\n[REST Client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) allows you to send HTTP requests and view the responses directly in VS Code. This extension supports a wide range of formats and authorization and should work with most setups.\n\n9. One Dark Pro\n[One Dark Pro](https://marketplace.visualstudio.com/items?itemName=zhuangtongfa.Material-theme) is one of the most popular VS Code themes and with very good reason. It provides a clean theme with a nice palette that has great contrast and is very comfortable to use on a daily basis.\n \n10. Fira Code\n[Fira Code](https://github.com/tonsky/FiraCode) is not a traditional VS Code extension and might take a couple more steps to set up, but it's a superb programming font with ligatures that will help you scan code faster once you get used to it.\n\n**Image credit:** [Fotis Fotopoulos](https://unsplash.com/@ffstop?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/code?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\n",
"tags": [
"devtools",
"vscode"
]
},
"meta": {
"hash": "2dd00656f3a19b08dd10877431101751009c00b0658dc5d3acab61e11fea21e3",
"firstSeen": "1577090516",
"lastUpdated": "1579272458",
"updateCount": 6,
"authorCount": 2
}
},
{
"id": "4-seo-tips-for-developers",
"title": "4 SEO tips for developers",
"type": "blog.list",
"attributes": {
"fileName": "4-seo-tips-for-developers.md",
"cover": "blog_images/4-seo-tips-for-developers.jpg",
"excerpt": "As time goes by, SEO is becoming increasingly relevant, but most web developers seem to have little experience with it. Here are 4 actionable SEO tips you can implement today.",
"authors": [
"chalarangelo"
],
"text": "SEO is becoming increasingly relevant as the internet keeps growing. While most web developers usually have little experience with SEO, it is not particularly difficult to handle some of the basics. Here are my top SEO tips for web developers:\n\n1. Craft user-friendly URLs and map the appropriately\nFirst and foremost, start at the very beginning, which is your URL slugs. For URL slugs the rule is that you want them to be human-readable, with words separated by dashes and with no random letters or digits added. Secondly, it's a good idea to make sure that parts of your URLs match to a logical structure in your website (e.g. `/blog/posts/awesome-list-of-seo-tips`). Finally, take the time to build a sitemap and redirect any broken or old URLs to new ones. This will help reduce 404 pages.\n\n2. Use structured data to help Google understand your pages\nStructured data is what Google uses to power its featured snippets, those little cards that appear at the top of certain searches. It's a good idea to set up structured data for your pages, which will help you rank higher in search results and possibly even land a featured snippet every once in a while. Just make sure to find the appropriate structured data type and include it in your page and you should be good to go.\n\n3. Set up Google Analytics and Google Search Console\nThis is hardly a new tip, but I think it deserves a spot on the list, as both of these tools are extremely important. Google Analytics allows you to track user behavior and gather data that can help you identify problems and opportunities, while Google Search Console is helpful for figuring out what users are searching for before landing on your website.\n\n4. Keep an eye on your markup, performance and accessibility\nLast but not least, something that is probably already on your list, is optimizing your code. This includes everything from writing semantic markup and keeping requests to a minimum to optimizing for all device types, making your website accessible and ensuring fast load times. Keep in mind that websites have many moving parts that evolve and change over time, so it's a good idea to audit your website often with a tool like Lighthouse.\n\n**Image credit:** [timJ](https://unsplash.com/@the_roaming_platypus?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/code?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\n",
"tags": [
"seo",
"webdev"
]
},
"meta": {
"hash": "ebc2337246ca7925e763034b8f5718f6276afd9252856cad56eff5f6d6ba25f1",
"firstSeen": "1579265475",
"lastUpdated": "1579271771",
"updateCount": 3,
"authorCount": 2
}
},
{
"id": "breaking-react",
"title": "Breaking React - a common pattern to avoid",
"type": "blog.story",
"attributes": {
"fileName": "breaking-react.md",
"cover": "blog_images/breaking-react.jpg",
"excerpt": "As powerful as React is, it is also quite fragile at places. Did you know that just a few lines are more than enough to break your entire React application?",
"authors": [
"chalarangelo"
],
"text": "I am by no means an expert React engineer, but I have a couple years of experience under my belt. While React is an extremely powerful library for building user interfaces, it is also quite fragile at places. A very common bug I have encountered is caused by direct DOM manipulation in combination with React. This is not exactly an anti-pattern, but under the right circumstances it can break your entire React application and might be hard to debug. \n\nHere's [a minimal example](https://codepen.io/chalarangelo/pen/jOEojVJ?editors=0010) of how one can reproduce this bug, before we dive into explaining the problem and how to fix it:\n\n```jsx\nconst destroyElement = () => \n document.getElementById('app').removeChild(document.getElementById('my-div'));\n\nconst App = () => {\n const [elementShown, updateElement] = React.useState(true);\n \n return (\n <div id='app'>\n <button onClick={() => destroyElement()}>\n Delete element via querySelector\n </button>\n <button onClick={() => updateElement(!elementShown)}>\n Update element and state\n </button>\n { elementShown ? <div id=\"my-div\">I am the element</div> : null }\n </div>\n );\n};\n\nReactDOM.render(<App />, document.getElementById('root'));\n```\n\nThis looks like a pretty simple React application, with a container, two buttons and a state variable. However, it will crash if you click the button that calls `destroyElement()` and then click the other button. _Why?_ you might ask. The issue here might not be immediately obvious, but if you look at your browser console you will notice the following exception:\n\n```\nUncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.\n```\n\nThis might still be cryptic, so let me explain what is going on. React uses its own representation of the DOM, called a virtual DOM, in order to figure out what to render. Usually, the virtual DOM will match the current DOM structure and React will process changes in props and state, updating the virtual DOM and then sending the necessary changes to the real DOM. \n\nHowever, in this case React's virtual DOM and the real DOM are different, because of `destroyElement()` removing the `#my-div` element. As a result, when React tries to update the real DOM with the changes from the virtual DOM, the `#my-div` element cannot be removed as it doesn't exist anymore. This results in the above exception being thrown and your application breaking.\n\nThis example is short and easy to resolve, by refactoring `destroyElement()` to be part of the `App` component and interact with its state, yet it showcases how fragile React can be under circumstances. Having a shared codebase, with many developers working on different things, can lead to issues like this being introduced and tracking them down can be rather tricky, which is why you might want to be very careful when directly manipulating the DOM when you use React.\n\n**Image credit:** [Julia Joppien](https://unsplash.com/@vitreous_macula?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/code?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\n",
"tags": [
"react",
"debugging"
]
},
"meta": {
"hash": "633fa8b4636401636d8bcf368f6967b96f50b65be845c9dd923a49e897fba771",
"firstSeen": "1580380519",
"lastUpdated": "1580380519",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "copy-text-to-clipboard-with-javascript",
"title": "How can I copy text to clipboard with JavaScript?",
"type": "blog.question",
"attributes": {
"fileName": "copy-text-to-clipboard-with-javascript.md",
"cover": "blog_images/copy-text-to-clipboard-with-javascript.jpg",
"excerpt": "Learn how to programmatically copy text to clipboard with a few lines of JavaScript and level up your web development skills.",
"authors": [
"chalarangelo"
],
"text": "**Core functionality**\n\nA very common need when building websites is the ability to copy text to clipboard with a single button click. Javascript can easily do this in five short steps:hout the user selecting it or hitting the appropriate key combination on their keyboard. Javascript can easily do this in five short steps:\n\n1. Create a` <textarea>` element to be appended to the document. Set its value to the string that we want to copy to the clipboard.\n2. Append said `<textarea>` element to the current HTML document.\n3. Use `HTMLInputElement.select()` to select the contents of the `<textarea>` element.\n4. Use `Document.execCommand('copy')` to copy the contents of the `<textarea>` to the clipboard.\n5. Remove the `<textarea>` element from the document.\n\nThe simplest version of this method looks something like this:\n\n```js\nconst copyToClipboard = str => {\n const el = document.createElement('textarea');\n el.value = str;\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n};\n```\n\nBear in mind that this method will not work everywhere, but only as a result of a user action (e.g. inside a `click` event listener), due to the way `Document.execCommand()` works.\n\n**Hide the appended element**\n\nThe above method, while functional, might have some issues such as flashing when appending and removing the `<textarea>`, a problem that is even more apparent when considering accessibility. A major improvement to this method comes from adding some CSS to make the element invisible and restrict editing by users:\n\n```js\nconst copyToClipboard = str => {\n const el = document.createElement('textarea');\n el.value = str;\n el.setAttribute('readonly', '');\n el.style.position = 'absolute';\n el.style.left = '-9999px';\n document.body.appendChild(el);\n el.select();\n document.execCommand('copy');\n document.body.removeChild(el);\n};\n```\n\n**Save and restore the original document's selection**\n\nThe final consideration before wrapping this up is respecting the user's previous interaction with the website, like having already selected some content. Luckily, we can now use some modern Javascript methods and properties like `DocumentOrShadowRoot.getSelection()`, `Selection.rangeCount`, `Selection.getRangeAt()`, `Selection.removeAllRanges()` and `Selection.addRange()` to save and restore the original document selection. You can find the final code with these improvements implemented in the [copyToClipboard snippet](/js/s/copy-to-clipboard/).\n\n**Image credit:** [Kaitlyn Baker](https://unsplash.com/@kaitlynbaker?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/code?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\n",
"tags": [
"javascript",
"browser"
]
},
"meta": {
"hash": "9a5b35e84ff9b2b86e943e3a30d1f34cef1272fdf712a85d637d53c7fbd40cc5",
"firstSeen": "1579513283",
"lastUpdated": "1579513283",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "javascript-for-in-for-of-foreach",
"title": "What is the difference between JavaScript's for...in, for...of and forEach?",
"type": "blog.question",
"attributes": {
"fileName": "javascript-for-in-for-of-foreach.md",
"cover": "blog_images/javascript-for-in-for-of-foreach.jpg",
"excerpt": "Learn the differences between the three most commonly used iteration methods offered by JavaScript, which often confuse beginners and veterans alike.",
"authors": [
"chalarangelo"
],
"text": "`for...in` is used to iterate over all enumerable properties of an object, including inherited enumerable properties. \nThis iteration statement can be used with arrays strings or plain objects, but not with `Map` or `Set` objects.\n\n```js\nfor (let prop in ['a', 'b', 'c']) \n console.log(prop); // 0, 1, 2 (array indexes)\n\nfor (let prop in 'str') \n console.log(prop); // 0, 1, 2 (string indexes)\n\nfor (let prop in {a: 1, b: 2, c: 3}) \n console.log(prop); // a, b, c (object property names)\n\nfor (let prop in new Set(['a', 'b', 'a', 'd'])) \n console.log(prop); // undefined (no enumerable properties)\n```\n\n`for...of` is used to iterate over iterable objects, iterating over their values instead of their properties.\nThis iteration statement can be used with arrays, strings, `Map` or `Set` objects, but not with plain objects.\n\n```js\nfor (let val of ['a', 'b', 'c']) \n console.log(val); // a, b, c (array values)\n\nfor (let val of 'str') \n console.log(val); // s, t, r (string characters)\n\nfor (let val of {a: 1, b: 2, c: 3}) \n console.log(prop); // TypeError (not iterable)\n\nfor (let val of new Set(['a', 'b', 'a', 'd'])) \n console.log(val); // a, b, d (Set values)\n```\n\nFinally, `forEach()` is a method of the `Array` prototype, which allows you to iterate over the elements of an array.\nWhile `forEach()` only iterates over arrays, it can access both the value and the index of each element while iterating.\n\n```js\n['a', 'b', 'c'].forEach(\n val => console.log(val) // a, b, c (array values)\n);\n\n['a', 'b', 'c'].forEach(\n (val, i) => console.log(i) // 0, 1, 2 (array indexes)\n);\n```\n\n**Image credit:** [Tim Stief](https://unsplash.com/@timstief?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/code?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\n",
"tags": [
"javascript",
"array",
"object",
"iterator"
]
},
"meta": {
"hash": "af1563c13c9cfc4f3ca9ab6c06c0e23579f134f0a4c37220e95d75eb785f943b",
"firstSeen": "1579507951",
"lastUpdated": "1580888902",
"updateCount": 4,
"authorCount": 2
}
},
{
"id": "javascript-iterators",
"title": "What are JavaScript Iterators and where can I use them?",
"type": "blog.question",
"attributes": {
"fileName": "javascript-iterators.md",
"cover": "blog_images/javascript-iterators.jpg",
"excerpt": "Learn how the new JavaScript ES6 Iterators work and how you can use them to level up your programming projects by understanding these short code examples.",
"authors": [
"chalarangelo"
],
"text": "JavaScript iterators were introduced in ES6 and they are used to loop over a sequence of values, usually some sort of collection. By definition, an iterator must implement a `next()` function, that returns an object in the form of `{ value, done }` where `value` is the next value in the iteration sequence and `done` is a boolean determining if the sequence has already been consumed.\n\nA very simple iterator with practical use in a real-world project could be as follows:\n\n```js\nclass LinkedList {\n constructor(data) {\n this.data = data;\n }\n\n firstItem() {\n return this.data.find(i => i.head);\n }\n\n findById(id) {\n return this.data.find(i => i.id === id);\n }\n\n [Symbol.iterator]() {\n let item = {next: this.firstItem().id};\n return {\n next: () => {\n item = this.findById(item.next);\n if(item) {\n return {value: item.value, done: false};\n }\n return {value: undefined, done: true};\n }\n };\n }\n}\n\nconst myList = new LinkedList([\n {id: 'a10', value: 'First', next: 'a13', head: true },\n {id: 'a11', value: 'Last', next: null, head: false },\n {id: 'a12', value: 'Third', next: 'a11', head: false },\n {id: 'a13', value: 'Second', next: 'a12', head: false }\n]);\n\nfor(let item of myList) {\n console.log(item); // 'First', 'Second', 'Third', 'Last'\n}\n```\n\nIn the above example, we implement a `LinkedList` data structure, that internally uses a `data` array where each item has a `value`, alongside some implementation-specific properties used to determine its position in the sequence. Objects constructed from this class are not iterable by default, so we define an iterator via the use of `Symbol.iterator` and set it up so that the returned sequence is in order based on the internal implementation of the class, while the returned items only return their `value`. \n\nOn a related note, iterators are just functions, meaning they can be called like any other function (e.g. to delegate the iteration to an existing iterator), while also not being restricted to the `Symbol.iterator` name, allowing us to define multiple iterators for the same object. Here's an example of these concepts at play:\n\n```js\nclass SpecialList {\n constructor(data) {\n this.data = data;\n }\n\n [Symbol.iterator]() {\n return this.data[Symbol.iterator]();\n }\n\n values() {\n return this.data\n .filter(i => i.complete)\n .map(i => i.value)\n [Symbol.iterator]();\n }\n}\n\nconst myList = new SpecialList([\n {complete: true, value: 'Lorem ipsum'},\n {complete: true, value: 'dolor sit amet'},\n {complete: false},\n {complete: true, value: 'adipiscing elit'}\n]);\n\nfor(let item of myList) {\n console.log(item); // The exact data passed to the SpecialList constructor above\n}\n\nfor(let item of myList.values()) {\n console.log(item); // 'Lorem ipsum', 'dolor sit amet', 'adipiscing elit'\n}\n```\n\nIn this example, we use the native array iterator of the `data` object to make our `SpecialList` iterable, returning the exact values of the `data` array. Meanwhile, we also define a `values` method, which is an iterator itself, using `Array.prototype.filter()` and `Array.prototype.map()` on the `data` array, then finally returning the `Symbol.iterator` of the result, allowing iteration only over non-empty objects in the sequence and returning just the `value` for each one.\n\n\n**Image credit:** [Daniele Levis Pelusi](https://unsplash.com/@yogidan2012?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/code?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\n",
"tags": [
"javascript",
"array",
"object",
"iterator"
]
},
"meta": {
"hash": "0b63d58f3ecd1d4dc6d3007629ce4e4a570dc15c09f09edcff6ef6a31a04bfc2",
"firstSeen": "1581851360",
"lastUpdated": "1581851360",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "javascript-memoization",
"title": "Where and how can I use memoization in JavaScript?",
"type": "blog.question",
"attributes": {
"fileName": "javascript-memoization.md",
"cover": "blog_images/javascript-memoization.jpg",
"excerpt": "Learn different ways to memoize function calls in JavaScript as well as when to use memoization to get the best performance results.",
"authors": [
"chalarangelo"
],
"text": "Memoization is a commonly used technique that you can use to speed up your code significantly. It uses a cache to store results, so that subsequent calls of time-consuming functions do not perform the same work another time. Based on this definition, we can easily extract some criteria that can help us decide when to use memoization in our code:\n\n- Memoization should be mainly used to speed up slow-performing, costly or time-consuming function calls\n- Memoization speeds up subsequent calls, so it is best used when you anticipate multiple calls of the same function under the same circumstances\n- Memoization stores results in memory, therefore it should be avoided when the same function is called multiple times under very different circumstances\n\nA simple, object-oriented example of implementing memoization could be as follows:\n\n```js\nclass MyObject {\n constructor(data) {\n this.data = data;\n this.data[this.data.length - 2] = { value: 'Non-empty' };\n }\n\n firstNonEmptyItem() {\n return this.data.find(v => !!v.value);\n }\n\n firstNonEmptyItemMemo() {\n if (!this.firstNonEmpty)\n this.firstNonEmpty = this.data.find(v => !!v.value);\n return this.firstNonEmpty;\n }\n}\n\nconst myObject = new MyObject(Array(2000).fill({ value: null }));\n\nfor (let i = 0; i < 100; i ++)\n myObject.firstNonEmptyItem(); // ~4000ms\nfor (let i = 0; i < 100; i ++)\n myObject.firstNonEmptyItemMemo(); // ~70ms\n```\n\nThe above example showcases a way to implement memoization inside a class, however it makes the assumptions that the `data` structure will not be altered over the lifecycle of the object and that this is the only expensive function call we will make, so it cannot be reused. It also doesn't account for arguments being passed to the function, which would alter the result. A functional approach that would work with any given function and also account for arguments can be found in the form of the [memoize snippet](/js/s/memoize/), which uses a `Map` to store different values. \n\nWe still recommend using that snippet as the primary way to memoize a function, however JavaScript's [Proxy object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) provides an interesting alternative via the use of the `handler.apply()` trap, which can be used for this purpose as follows:\n\n```js\nconst memoize = fn => new Proxy(fn, {\n cache: new Map(),\n apply (target, thisArg, argsList) {\n let cacheKey = argsList.toString();\n if(!this.cache.has(cacheKey))\n this.cache.set(cacheKey, target.apply(thisArg, argsList));\n return this.cache.get(cacheKey);\n }\n});\n\nconst fibonacci = n => (n <= 1 ? 1 : fibonacci(n - 1) + fibonacci(n - 2));\nconst memoizedFibonacci = memoize(fibonacci);\n\nfor (let i = 0; i < 100; i ++)\n fibonacci(30); // ~5000ms\nfor (let i = 0; i < 100; i ++)\n memoizedFibonacci(30); // ~50ms\n```\n\n\n**Image credit:** [Mark Tegethoff](https://unsplash.com/@tegethoff?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/code?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\n",
"tags": [
"javascript",
"function",
"memoization"
]
},
"meta": {
"hash": "35d0c102613d534ddb5aa96ef34da058c6fb29daac4d16ccdcee095007a45131",
"firstSeen": "1582813405",
"lastUpdated": "1582813405",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "javascript-singleton-proxy",
"title": "How can I implement a singleton in JavaScript?",
"type": "blog.question",
"attributes": {
"fileName": "javascript-singleton-proxy.md",
"cover": "blog_images/javascript-singleton-proxy.jpg",
"excerpt": "Learn how to implement a singleton, a commonly used software design pattern, in JavaScript using the Proxy object.",
"authors": [
"chalarangelo"
],
"text": "A singleton is an object-oriented software design pattern which ensures a given class is only ever instantiated once and can be quite useful in many different situations, such as creating global objects and components shared across an application. While JavaScript supports object-oriented programming, it doesn't seem to provide many simple options to implement this pattern. \n\nThe most flexible, albeit somewhat advanced, approach involves using the [Proxy object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). The Proxy object is used to define so-called traps, methods that allow the definition of custom behavior for certain operations such as property lookup, assignment etc. The singleton pattern dictates that the given class can only have one instance, which means that the most useful trap is `handler.construct()`, the trap for the `new` operator. \n\nAs the `handler` is itself an object, we can use it to store the unique instance of the class we want, if it has been instantiated, while also providing a trap for the `new` operator via `handler.construct()`. In doing so, we can create an object that can be easily reused for any class we want to convert into a singleton, while also allowing us to provide additional traps for any other operations we might want to customize. \n\nHere's the most basic version of a function that takes a `class` and converts it into a singleton, based on the above explanation:\n\n```js\nconst singletonify = (className) => {\n return new Proxy(className.prototype.constructor, {\n instance: null,\n construct: (target, argumentsList) => {\n if (!this.instance)\n this.instance = new target(...argumentsList);\n return this.instance;\n }\n });\n}\n```\n\nAnd here is a simple practical example to better understand what it does:\n\n```js\nclass MyClass {\n constructor(msg) {\n this.msg = msg;\n }\n\n printMsg() {\n console.log(this.msg);\n }\n}\n\nMySingletonClass = singletonify(MyClass);\n\nconst myObj = new MySingletonClass('first');\nmyObj.printMsg(); // 'first'\nconst myObj2 = new MySingletonClass('second');\nmyObj2.printMsg(); // 'first'\n```\n\nIn the above example, you can see that the second time `MySingletonClass` is instantiated, nothing happens, due to the fact that an instance already exists, so it is returned instead of a new object being created. While this is the minimum implementation of a `singletonify` function, it can easily be extended to modify the behavior even further or even use some of the data passed to the constructor in subsequent calls to update the `instance` it holds.\n\n\n**Image credit:** [David Watkis](https://unsplash.com/@david_watkis?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\n",
"tags": [
"javascript",
"object",
"function",
"pattern"
]
},
"meta": {
"hash": "c0fdcc7dd89958154b42f98bbf9d2d954b4ddf3135cf8c80e1441729c31911fd",
"firstSeen": "1582639323",
"lastUpdated": "1582639323",
"updateCount": 2,
"authorCount": 2
}
},
{
"id": "testing-stateful-ui-components",
"title": "An approach to testing stateful React components",
"type": "blog.story",
"attributes": {
"fileName": "testing-stateful-ui-components.md",
"cover": "blog_images/testing-stateful-ui-components.jpg",
"excerpt": "Testing stateful React components is by no means a difficult task, but did you know there is an elegant solution that doesn't involve testing state directly?",
"authors": [
"chalarangelo"
],
"text": "Some time ago, I was tasked with writing tests for a handful of React components, an otherwise mundane and uninspiring task, that somehow ended with a \"Eureka!\" moment for me. The specifics of the project and its components are of little importanc, however the key detail is that I was working with stateful React components that are used daily by a large team and, as such, are refactored and updated quite often.\n\nMy initial approach consisted of writing some simple tests, such as checking if the component is rendered properly and if certain events fire appropriately. In doing so, I was comparing state directly with the result I was expecting, having the component's code right next to my assertions. Of course, this isn't bad by anyone's standards, but for a codebase with many moving parts, it is not the greatest idea. Let me show you an example why:\n\n```js\ncontext('the component is initialized in a collapsed state', function() {\n let wrapper;\n beforeEach(function(){\n wrapper = mount(<StatefulComponent />);\n });\n\n it('component state.expanded is false', function() {\n expect(wrapper.state('expanded')).to.be.false;\n });\n});\n```\n\nIn this test, we check if the component's state has `expanded` equal to `false`. Our test will pass, as long as this simple condition is true. It's a very simple test that should be easy to understand even for someone completely unfamiliar with the codebase.\n\nHowever, over time the component's implementation might change. What happens if `expanded` in our state ends up meaning something different? Or worse yet, if it isn't reflected the same way in the interface?\n\nEnter my \"Eureka!\" moment:\n\n> The application's UI should always be considered the result of combining the component's props and state.\n\nThe above statement implies that a component's state can be considered a black box while testings, an abstraction layer that should not be accessed unless absolutely necessary. So, instead of the test presented above, we should be doing something more like this:\n\n```js\ncontext('the component is initialized in a collapsed state', function() {\n let wrapper;\n beforeEach(function(){\n wrapper = mount(<StatefulComponent />);\n });\n\n it('component does not have the expanded class', function() {\n expect(wrapper.find('div').hasClass('expanded')).to.be.false;\n });\n});\n```\n\nOur test is still easy to read and understand, but it's a better test in general. \n\nBy directly checking the DOM instead of the component's state, we provide information about the component's output to future code authors, instead of asking them to keep the existing implementation intact. It seems like a better way to document the component and it's easier to track future changes should someone refactor the UI in such a way that the DOM representation of the component is altered.\n\n**Image credit:** [Evan Clark](https://unsplash.com/@evanrclark?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)\n",
"tags": [
"react",
"testing"
]
},
"meta": {
"hash": "8a68806114f98a5da74a0785b6ccb29ed19398f9d1ecfb48ee8a6e195b6f322a",
"firstSeen": "1579161498",
"lastUpdated": "1579265244",
"updateCount": 3,
"authorCount": 2
}
}
],
"meta": {
"specification": "http://jsonapi.org/format/",
"type": "snippetArray",
"language": {
"short": "",
"long": ""
}
}
}