Update builder script
This commit is contained in:
@ -10,19 +10,14 @@ before_install:
|
||||
- npm install -g eslint
|
||||
script:
|
||||
- npm run linter
|
||||
- npm run extractor
|
||||
- npm run builder
|
||||
- npm run packager
|
||||
- npm run tester
|
||||
- npm run test
|
||||
- npm run extractor
|
||||
- npm run vscoder
|
||||
- npm run glossary:keymaker
|
||||
- npm run webber
|
||||
- npm run builder
|
||||
- npm run glossary:librarian
|
||||
after_success:
|
||||
- chmod +x .travis/push.sh
|
||||
- .travis/push.sh
|
||||
group: deprecated-2017Q4
|
||||
env:
|
||||
global:
|
||||
- secure: RucoyHikFKD7yQq7FBHxOpwYSHSFYUO7QS/5VEXvU55AMnHwB97aI0DcQSMa+XHaSFVsqd4fR7nAP+5H6GMW/lUhIdeXIGzehgBTfuNeQmng2djGgS1lWY9fEOsn2XEL7JlXMi2P5YdZDpOAfiiLqT3W8EaCWDdV60tkizbSQhig2R3exI/649AjmGkIws+NqoYqrEfNpnTvgxJkp2jNuKfBkr0aaVdYuxdI6Kf2KnipEeuKsKJFds+tTjduEUKTg7I8lNSB+tQ9wIHNTDZffZrzODzE2esAZtnflxhkGQ6q7fW8DEj0rheuer+yD4WBWfph1CIxTL6B3VZgT6XQXCu09XzqgRUack0KIS6SBRKjRYJymH3eKNlxZGPpk4s90bX0Qo0a0vvcT4g/iejyVb917pcn2LjRZmmsFQUfJOcCJgU6EUvqNpfM9SWV8fJhaPOacvUnzDxFav3eRdDHaZYgXf0tzJfLAjsTv7rFbLZEnpqtvyKbHrXYLf9sICyPlHbCy4L5KAfguu735v0YPXko5Aabl6PvGcfafyLxVUb/0Y5ot3pLtGVJflfHeqYz8qbkoqp5RovSvTXntx/vVlx20TSE/rQP2l6JUNt98sGFJ+yOZ3SkMnyMdjE1YqeEngxZdzukec2SM3PtnaWxSbxV8Ue1XnM8D5nzhTf4UI8=
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
# 30-seconds-of-code JavaScript Glossary
|
||||
|
||||
## Table of Contents
|
||||
## Contents
|
||||
|
||||
* [`AJAX`](#ajax)
|
||||
* [`API`](#api)
|
||||
@ -102,325 +102,450 @@
|
||||
* [`XML`](#xml)
|
||||
* [`Yarn`](#yarn)
|
||||
|
||||
|
||||
### AJAX
|
||||
|
||||
Asynchronous JavaScript and XML (known as AJAX) is a term that describes a new approach to using multiple technologies together in order to enable web applications to make quick updates to the user interface without reloading the entire browser page.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### API
|
||||
|
||||
API stands for Application Programming Interface and is a set of features and rules provided by a provided by a software to enable third-party software to interact with it.
|
||||
The code features of a web API usually include methods, properties, events or URLs.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Argument
|
||||
|
||||
An argument is a value passed as an input to a function and can be either a primitive or an object.
|
||||
In JavaScript, functions can also be passed as arguments to other functions.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Array
|
||||
|
||||
Arrays are used to store multiple values in a single variable.
|
||||
Arrays are ordered and each item in an array has a numeric index associated with it.
|
||||
JavaScript arrays are zero-indexed, meaning the first element's index is 0.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Asynchronous programming
|
||||
|
||||
Asynchronous programming is a way to allow multiple events to trigger code without waiting for each other.
|
||||
The main benefits of asynchronous programming are improved application performance and responsiveness.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Automatic semicolon insertion
|
||||
|
||||
Automatic semicolon insertion (ASI) is a JavaScript feature that allows developers to omit semicolons in their code.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Boolean
|
||||
|
||||
Booleans are one of the primitive data types in JavaScript.
|
||||
They represent logical data values and can only be `true` or `false`.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Callback
|
||||
|
||||
A callback function, also known as a high-order function, is a function that is passed into another function as an argument, which is then executed inside the outer function.
|
||||
Callbacks can be synchronous or asynchronous.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Character encoding
|
||||
|
||||
A character encoding defines a mapping between bytes and text, specifying how the sequenece of bytes should be interpreted.
|
||||
Two commonly used character encodings are ASCII and UTF-8.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Class
|
||||
|
||||
In object-oriented programming, a class is a template definition of an object's properties and methods.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Closure
|
||||
|
||||
A closure is the combination of a function and the lexical environment within which that function was declared.
|
||||
The closure allows a function to access the contents of that environment.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### CoffeeScript
|
||||
|
||||
CoffeeScript is a programming language inspired by Ruby, Python and Haskell that transpiles to JavaScript.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Constant
|
||||
|
||||
A constant is a value, associated with an identifier.
|
||||
The value of a constant can be accessed using the identifier and cannot be altered during execution.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Constructor
|
||||
|
||||
In class-based object-oriented programming, a constructor is a special type of function called to instantiate an object.
|
||||
Constructors often accept arguments that are commonly used to set member properties.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Continuous Deployment
|
||||
|
||||
Continuous Deployment follows the testing that happens during Continuous Integration and pushes changes to a staging or production system.
|
||||
Continuous Deployment ensures that a version of the codebase is accessible at all times.
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Continuous Integration
|
||||
|
||||
Continuous Integration (CI) is the practice of testing each change done to a codebase automatically and as early as possible.
|
||||
Two popular CI systems that integrate with GitHub are Travis CI and Circle CI.
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### CORS
|
||||
|
||||
Cross-Origin Resource Sharing (known as CORS) is a mechanism that uses extra HTTP headers to tell a browser to let a web application running at one domain have permission to access resources from a server at a different domain.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Cross-site scripting (XSS)
|
||||
|
||||
XSS refers to client-side code injection where the attacker injects malicious scripts into a legitimate website or web application.
|
||||
This is often achieved when the application does not validate user input and freely injects dynamic HTML content.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### CSS
|
||||
|
||||
CSS stands for Cascading Style Sheets and is a language used to style web pages.
|
||||
CSS documents are plaintext documents structured with rules, which consist of element selectors and property-value pairs that apply the styles to the specified selectors.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### CSV
|
||||
|
||||
CSV stands for Comma-Separated Values and is a storage format for tabular data.
|
||||
CSV documents are plaintext documents where each line represents a table row, with table columns separated by commas or some other delimiter (e.g. semicolons).
|
||||
The first line of a CSV document sometimes consists of the table column headings for the data to follow.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Currying
|
||||
|
||||
Currying is a way of constructing functions that allows partial application of a function's arguments.
|
||||
Practically, this means that a function is broken down into a series of functions, each one accepting part of the arguments.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Deserialization
|
||||
|
||||
Deserialization is the process of converting a format that has been transferred over a network and/or used for storage to an object or data structure.
|
||||
A common type of deserialization in JavaScript is the conversion of JSON string into an object.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### DNS
|
||||
|
||||
A DNS (Domain Name System) translates domain names to the IP addresses needed to find a particular computer service on a network.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### DOM
|
||||
|
||||
The DOM (Document Object Model) is a cross-platform API that treats HTML and XML documents as a tree structure consisting of nodes.
|
||||
These nodes (such as elements and text nodes) are objects that can be programmatically manipulated and any visible changes made to them are reflected live in the document.
|
||||
In a browser, this API is available to JavaScript where DOM nodes can be manipulated to change their styles, contents, placement in the document, or interacted with through event listeners.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Domain name registrar
|
||||
|
||||
A domain name registrar is a company that manages the reservation of internet domain names.
|
||||
A domain name registrar must be approved by a general top-level domain (gTLD) registry or a country code top-level domain (ccTLD) registry.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Domain name
|
||||
|
||||
A domain name is a website's address on the Internet, used primarily in URLs to identify the server for each webpage.
|
||||
A domain name consists of a hierarchical sequence of names, separated by dots and ending with an extension.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Element
|
||||
|
||||
A JavaScript representation of a DOM element commonly returned by `document.querySelector()` and `document.createElement()`.
|
||||
They are used when creating content with JavaScript for display in the DOM that needs to be programatically generated.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### ES6
|
||||
|
||||
ES6 stands for ECMAScript 6 (also known as ECMAScript 2015), a version of the ECMAScript specification that standardizes JavaScript.
|
||||
ES6 adds a wide variety of new features to the specification, such as classes, promises, generators and arrow functions.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Event-driven programming
|
||||
|
||||
Event-driven programming is a programming paradigm in which the flow of the program is determined by events (e.g. user actions, thread messages, sensor outputs).
|
||||
In event-driven applications, there is usually a main loop that listens for events and trigger callback functions accordingly when one of these events is detected.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Event loop
|
||||
|
||||
The event loop handles all asynchronous callbacks.
|
||||
Callbacks are queued in a loop, while other code runs, and will run one by one when the response for each one has been received.
|
||||
The event loop allows JavaScript to perform non-blocking I/O operations, despite the fact that JavaScript is single-threaded.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Express
|
||||
|
||||
Express is a backend framework, that provides a layer of fundamental web application features for Node.js.
|
||||
Some of its key features are routing, middleware, template engines and error handling.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Factory functions
|
||||
|
||||
In JavaScript, a factory function is any function, which is not a class or constructor, that returns a new object.
|
||||
Factory functions don't require the use of the `new` keyword.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### First-class function
|
||||
|
||||
A programming language is said to have first-class functions if it treats them as first-class citizens, meaning they can be passed as arguments, be returned as values from other functions, be assigned to variables and stored in data structures.
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Flexbox
|
||||
|
||||
Flexbox is a one-dimensional layout model used to style websites as a property that could advance space distribution between items and provide powerful alignment capabilities.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Function
|
||||
|
||||
Functions are self-contained blocks of code with their own scope, that can be called by other code and are usually associated with a unique identifier.
|
||||
Functions accept input in the form of arguments and can optionally return an output (if no `return` statement is present, the default value of `undefined` will be returned instead).
|
||||
JavaScript functions are also objects.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Functional programming
|
||||
|
||||
Functional programming is a paradigm in which programs are built in a declarative manner using pure functions that avoid shared state and mutable data.
|
||||
Functions that always return the same value for the same input and don't produce side effects are the pillar of functional programming.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Functor
|
||||
|
||||
A Functor is a data type common in functional programming that implements a `map` method.
|
||||
The `map` method takes a function and applies it to the data in the Functor, returning a new instance of the Functor with the result.
|
||||
JavaScript `Array`s are an example of the Functor data type.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Garbage collection
|
||||
|
||||
Garbage collection is a form of automatic memory management.
|
||||
It attempts to reclaim memory occupied by objects that are no longer used by the program.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Git
|
||||
|
||||
Git is an open-source version control system, used for source code management.
|
||||
Git allows users to copy (clone) and edit code on their local machines, before merging it into the main code base (master repository).
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Higher-order function
|
||||
|
||||
Higher-order functions are functions that either take other functions as arguments, return a function as a result, or both.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Hoisting
|
||||
|
||||
Hoisting is JavaScript's default behavior of adding declarations to memory during the compile phase.
|
||||
Hoisting allows for JavaScript variables to be used before the line they were declared on.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### HTML
|
||||
|
||||
HTML stands for HyperText Markup Language and is a language used to structure web pages.
|
||||
HTML documents are plaintext documents structured with elements, which are surrounded by `<>` tags and optionally extended with attributes.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### HTTP and HTTPS
|
||||
|
||||
The HyperText Transfer Protocol (HTTP) is the underlying network protocol that enables transfer of hypermedia documents on the Web, usually between a client and a server.
|
||||
The HyperText Transfer Protocol Secure (HTTPS) is an encrypted version of the HTTP protocol, that uses SSL to encrypt all data transferred between a client and a server.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Integer
|
||||
|
||||
Integers are one of the primitive data types in Javascript.
|
||||
They represent a numerical value that has no fractional component.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Integration testing
|
||||
|
||||
Integration testing is a type of software testing, used to test groups of units/components of a software.
|
||||
The purpose of integration tests are to validate that the units/components interact with each other as expected.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### IP
|
||||
|
||||
An IP address is a number assigned to a device connected to a network that uses the Internet protocol.
|
||||
Two IP versions are currently in use - IPv4, the older version of the communication protocol (e.g. 192.168.1.100) and IPv6, the newest version of the communication protocol which allows for many different IP addresses (e.g. 0:0:0:0:ffff:c0a8:164).
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### jQuery
|
||||
|
||||
jQuery is a frontend JavaScript library, that simplifies DOM manipulation, AJAX calls and Event handling.
|
||||
jQuery uses its globally defined function, `$()`, to select and manipulate DOM elements.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### JSON
|
||||
|
||||
JSON (JavaScript Object Notation) is a format for storing and exchanging data.
|
||||
It closely resembles the JavaScript object syntax, however some data types, such as dates and functions, cannot be natively represented and need to be serialized first.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### MDN
|
||||
|
||||
MDN Web Docs, formerly known as Mozilla Developer Network, is the official Mozilla website for development documentation of web standards and Mozilla projects.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Module
|
||||
|
||||
Modules are independent, self-contained pieces of code that can be incorporated into other pieces of code.
|
||||
Modules improve maintainability and reusability of the code.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### MongoDB
|
||||
|
||||
MongoDB is a NoSQL database model that stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Mutable value
|
||||
|
||||
Mutable value is a type of variable that can be changed once created.
|
||||
Objects are mutable as their state can be modified after they are created.
|
||||
Primitive values are not mutable as we perform reassignment once we change them.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### MVC
|
||||
|
||||
MVC stands for Model-View-Controller and is a software design pattern, emphasizing separation of concerns (logic and display).
|
||||
The Model part of the MVC pattern refers to the data and business logic, the View handles the layout and display, while the Controller routes commands to the model and view parts.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Node.js
|
||||
|
||||
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.
|
||||
Node.js can execute JavaScript code outside of the browser and can be used to develop web backends or standalone applications.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### NoSQL
|
||||
|
||||
NoSQL databases provide a mechanism to create, update, retrieve and calculate data that is stored in models that are non-tabular.
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Npm
|
||||
|
||||
Npm is a package manager for the JavaScript programming language and the default package manager for Node.js.
|
||||
It consists of a command-line client and the npm registry, an online database of packages.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Object-oriented programming
|
||||
|
||||
Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which may contain both data and procedures which can be use to operate on them.
|
||||
JavaScript supports Object-oriented programming both via prototypes and classes.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Object
|
||||
|
||||
Objects are data structures that contain data and instructions for working with the data.
|
||||
Objects consist of key-value pairs, where the keys are alphanumeric identifiers and the values can either be primitives or objects.
|
||||
JavaScript functions are also objects.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Prepared statements
|
||||
|
||||
In databases management systems, prepared statements are templates that can be used to execute queries with the provided values substituting the template's parameters.
|
||||
Prepared statements offer many benefits, such as reusability, maintainability and higher security.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Promise
|
||||
|
||||
The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
|
||||
A Promise can be in one of these states: pending(initial state, neither fulfilled nor rejected), fulfilled(operation completed successfully), rejected(operation failed).
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Prototype-based programming
|
||||
|
||||
Prototype-based programming is a style of object-oriented programming, where inheritance is based on object delegation, reusing objects that serve as prototypes.
|
||||
Prototype-based programming allows the creation of objects before defining their classes.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Pseudo-class
|
||||
|
||||
In CSS, a pseudo-class is used to define a special state of an element and can be used as a selector in combination with an id, element or class selector.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Pseudo-element
|
||||
|
||||
In CSS, a pseudo-element is used to style specific parts of an element and can be used as a selector in combination with an id, element or class selector.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### PWA
|
||||
|
||||
Progressive Web App (known as PWA) is a term used to describe web applications that load like regular websites but can offer the user functionality such as working offline, push notifications, and device hardware access that were traditionally available only to native mobile applications.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### React
|
||||
|
||||
React is a frontend framework, that allows developers to create dynamic, component-based user interfaces.
|
||||
React separates view and state, utilizing a virtual DOM to update the user interface.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Recursion
|
||||
|
||||
Recursion is the repeated application of a process.
|
||||
@ -428,164 +553,232 @@ In JavaScript, recursion involves functions that call themselves repeatedly unti
|
||||
The base condition breaks out of the recursion loop because otherwise the function would call itself indefinitely.
|
||||
Recursion is very useful when working with nested data, especially when the nesting depth is dynamically defined or unkown.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Regular expressions
|
||||
|
||||
Regular expressions (known as regex or regexp) are patterns used to match character combinations in strings.
|
||||
JavaScript provides a regular expression implementation through the `RegExp` object.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Repository
|
||||
|
||||
In a version control system, a repository (or repo for short) is a data structure that stores metadata for a set of files (i.e. a project).
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Responsive web design
|
||||
|
||||
Responsive web design is a web development concept aiming to provide optimal behavior and performance of websites on all web-enabled devices.
|
||||
Responsive web design is usually coupled with a mobile-first approach.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Scope
|
||||
|
||||
Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Selector
|
||||
|
||||
A CSS selector is a pattern that is used to select and/or style one or more elements in a document, based on certain rules.
|
||||
The order in which CSS selectors apply styles to elements is based on the rules of CSS specificity.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### SEO
|
||||
|
||||
SEO stands for Search Engine Optimization and refers to the process of improving a website's search rankings and visibility.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Serialization
|
||||
|
||||
Serialization is the process of converting an object or data structure into a format suitable for transfer over a network and/or storage.
|
||||
A common type of serialization in JavaScript is the conversion of an object into a JSON string.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Shadow DOM
|
||||
|
||||
Shadow DOM allows you to attach hidden DOM trees to elements in the normal DOM tree, which are included in the document rendering, but excluded from the main document DOM tree.
|
||||
A shadow DOM tree will start with a shadow root, to which you can attach any elements you want, just like in a regular DOM.
|
||||
Examples of shadow DOM uses are the `<video>`/`<audio>` elements and the simple `<input type="range">` element.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### SQL injection
|
||||
|
||||
SQL injection is a code injection technique, used to attack data-driven applications.
|
||||
SQL injections get their name from the SQL language and mainly target data stored in relational databases.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### SQL
|
||||
|
||||
SQL stands for Structured Query Language and is a language used to create, update, retrieve and calculate data in table-based databases.
|
||||
SQL databases use a relational database model and are particularly useful in handlind structured data with relations between different entities.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### SSL
|
||||
|
||||
Secure Sockets Layer, commonly known as SSL or TLS, is a set of protocols and standards for transferring private data across the Internet.
|
||||
SSL uses a cryptographic system that uses two keys to encrypt data.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Stream
|
||||
|
||||
A stream is a sequence of data made available over time, often due to network transmission or storage access times.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Strict mode
|
||||
|
||||
JavaScript's strict mode is a JavaScript feature that allows developers to use a more restrictive variant of JavaScript and it can be enabled by adding `'use strict';` at the very top of their code.
|
||||
Strict mode elimiated some silent errors, might improve performance and changes the behavior of `eval` and `arguments` among other things.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### String
|
||||
|
||||
Strings are one of the primitive data types in JavaScript.
|
||||
They are sequences of characters and are used to represent text.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### SVG
|
||||
|
||||
SVG stands for Scalable Vector Graphics and is a 2D vector image format based on an XML syntax.
|
||||
SVG images can scale infinitely and can utilize clipping, masking, filters, animations etc.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Template literals
|
||||
|
||||
Template literals are strings that allow embedded expressions.
|
||||
They support multi-line strings, expression interpolation and nesting.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### TypeScript
|
||||
|
||||
TypeScript is a superset of JavaScript, adding optional static typing to the language.
|
||||
TypeScript compiles to plain JavaScript.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Unit testing
|
||||
|
||||
Unit testing is a type of software testing, used to test individual units/components of a software.
|
||||
The purpose of unit tests are to validate that each individual unit/component performs as designed.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### URI
|
||||
|
||||
URI stands for Uniform Resource Identifier and is a text string referring to a resource.
|
||||
A common type of URI is a URL, which is used for the identification of resources on the Web.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### URL
|
||||
|
||||
URL stands for Uniform Resource Locator and is a text string specifying where a resource can be found on the Internet.
|
||||
In the HTTP protocol, URLs are the same as web addresses and hyperlinks.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### UTF-8
|
||||
|
||||
UTF-8 stands for UCS Transformation Format 8 and is a commonly used character encoding.
|
||||
UTF-8 is backwards compatible with ASCII and can represent any standard Unicode character.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Value vs reference
|
||||
|
||||
When passing a variable by value, a copy of the variable is made, meaning that any changes made to the contents of the variable will not be reflected in the original variable.
|
||||
When passing a variable by reference, the memory address of the actual variable is passed to the function or variable, meaning that modifying the variable's contents will be reflected in the original variable.
|
||||
In JavaScript primitive data types are passed by value while objects are passed by reference.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Variable
|
||||
|
||||
A variable is a storage location, associated with an identifier and containing a value.
|
||||
The value of a variable can be referred using the identifier and can be altered during execution.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Viewport
|
||||
|
||||
A viewport is a polygonal (usually rectangular) area in computer graphics that is currently being viewed.
|
||||
In web development and design, it refers to the visible part of the document that is being viewed by the user in the browser window.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Vue
|
||||
|
||||
Vue.js is a progressive frontend framework for building user interfaces.
|
||||
Vue.js separates view and state, utilizing a virtual DOM to update the user interface.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### WebAssembly
|
||||
|
||||
WebAssembly (WA) is a web standard that defines an assembly-like text format and corresponding binary format for executalbe code in web pages.
|
||||
WebAssembly is meant to complement JavaScript and improve its performance to match native code performance.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Web Components
|
||||
|
||||
Web Components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use on web pages and apps.
|
||||
Building custom components using these standards means that you can use them across modern browsers regardless of any JavaScript library or framework.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### WebGL
|
||||
|
||||
WebGL stands for Web Graphics Library and is a JavaScript API that can be used for drawing interactive 2D and 3D graphics.
|
||||
WebGL is based on OpenGL and can be invoked within HTML `<canvas>` elements, which provide a rendering surface.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### WebRTC
|
||||
|
||||
WebRTC stands for Web Real-Time Communication and is an API that can be used for video-chat, voice-calling and P2P-file-sharing web apps.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### WebSockets
|
||||
|
||||
WebSockets is a protocol that allows for a persistent client-server TCP connection.
|
||||
The WebSocket protocol uses lower overheads, facilitating real-time data transfer between client and server.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### XHTML
|
||||
|
||||
XHTML stands for EXtensible HyperText Markup Language and is a language used to structure web pages.
|
||||
XHTML is a reformulation of the HTML document structure as an application of XML.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### XML
|
||||
|
||||
XML stands for eXtensible Markup Language and is a generic markup language specified by the W3C.
|
||||
XML documents are plaintext documents structured with user-defined tags, surrounded by `<>` and optionally extended with attributes.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### Yarn
|
||||
|
||||
Yarn is a package manager made by Facebook.
|
||||
It can be used as an alternative to the npm package manager and is compatible with the public NPM registry.
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
@ -6,15 +6,13 @@
|
||||
"module": "dist/_30s.esm.js",
|
||||
"sideEffects": false,
|
||||
"scripts": {
|
||||
"glossary:librarian": "node ./scripts/glossary/library.js",
|
||||
"glossary:keymaker": "node ./scripts/glossary/keyword.js",
|
||||
"builder": "node ./scripts/build.js",
|
||||
"linter": "node ./scripts/lint.js",
|
||||
"extractor": "node ./scripts/extract.js",
|
||||
"builder": "node ./scripts/build.js",
|
||||
"webber": "gatsby build",
|
||||
"webber:dev": "gatsby develop",
|
||||
"webber:serve": "gatsby serve",
|
||||
"tester": "node ./scripts/tdd.js",
|
||||
"extractor": "node ./scripts/extract.js",
|
||||
"vscoder": "node ./scripts/vscodegen.js",
|
||||
"packager": "node ./scripts/module.js",
|
||||
"test": "jest --verbose --coverage"
|
||||
|
||||
263
scripts/build.js
263
scripts/build.js
@ -1,5 +1,5 @@
|
||||
/*
|
||||
This is the builder script that generates the README and SNIPPETS_ARCHIVE files.
|
||||
This is the builder script that generates the README files.
|
||||
Run using `npm run builder`.
|
||||
*/
|
||||
// Load modules
|
||||
@ -9,75 +9,33 @@ const { green, red } = require('kleur');
|
||||
const util = require('./util');
|
||||
const markdown = require('markdown-builder');
|
||||
const { headers, misc, lists } = markdown;
|
||||
const config = require('../config');
|
||||
|
||||
// Paths
|
||||
const SNIPPETS_PATH = './snippets';
|
||||
const SNIPPETS_ARCHIVE_PATH = './snippets_archive';
|
||||
const STATIC_PARTS_PATH = './static-parts';
|
||||
const SNIPPETS_PATH = `./${config.snippetPath}`;
|
||||
const SNIPPETS_ARCHIVE_PATH = `./${config.snippetArchivePath}`;
|
||||
const GLOSSARY_PATH = `./${config.glossaryPath}`;
|
||||
const STATIC_PARTS_PATH = `./${config.staticPartsPath}`;
|
||||
|
||||
const makeExamples = data => {
|
||||
data =
|
||||
data.slice(0, data.lastIndexOf('```js')).trim() +
|
||||
misc.collapsible(
|
||||
'Examples',
|
||||
data.slice(data.lastIndexOf('```js'), data.lastIndexOf('```')) +
|
||||
data.slice(data.lastIndexOf('```'))
|
||||
);
|
||||
return `${data}\n<br>${misc.link('⬆ Back to top', misc.anchor('Contents'))}\n\n`;
|
||||
};
|
||||
|
||||
if (util.isTravisCI() && /^Travis build: \d+/g.test(process.env['TRAVIS_COMMIT_MESSAGE'])) {
|
||||
// Terminate if parent commit is a Travis build
|
||||
if (
|
||||
util.isTravisCI() &&
|
||||
/^Travis build: \d+/g.test(process.env['TRAVIS_COMMIT_MESSAGE'])
|
||||
) {
|
||||
console.log(
|
||||
`${green('NOBUILD')} README build terminated, parent commit is a Travis build!`
|
||||
`${green(
|
||||
'NOBUILD',
|
||||
)} README build terminated, parent commit is a Travis build!`,
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
if (
|
||||
util.isTravisCI() &&
|
||||
(process.env['TRAVIS_EVENT_TYPE'] === 'cron' || process.env['TRAVIS_EVENT_TYPE'] === 'api')
|
||||
) {
|
||||
console.log(`${green('ARCHIVE')} Cron job or custom build, building archive README!`);
|
||||
console.time('Builder');
|
||||
let snippets = {};
|
||||
// Synchronously read all snippets from snippets_archive folder and sort them as necessary (case-insensitive)
|
||||
try {
|
||||
const snippetFilenames = fs
|
||||
.readdirSync(SNIPPETS_ARCHIVE_PATH)
|
||||
.sort((a, b) => a.toLowerCase() - b.toLowerCase());
|
||||
// Store the data read from each snippet in the appropriate object
|
||||
for (const name of snippetFilenames.filter(s => s !== 'README.md'))
|
||||
snippets[name] = fs.readFileSync(path.join(SNIPPETS_ARCHIVE_PATH, name), 'utf8');
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During snippet loading: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
try {
|
||||
// Add the start static part
|
||||
let output =
|
||||
misc.image('Logo', '/logo.png') +
|
||||
headers.h1('Snippets Archive') +
|
||||
"These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are." +
|
||||
headers.h2('Table of Contents');
|
||||
|
||||
output += lists.ul(Object.entries(snippets), snippet =>
|
||||
misc.link(`\`${snippet[0].slice(0, -3)}\``, misc.anchor(snippet[0].slice(0, -3)))
|
||||
);
|
||||
output += misc.hr();
|
||||
|
||||
for (const snippet of Object.entries(snippets))
|
||||
output += makeExamples(snippet[1]);
|
||||
|
||||
// Write to the README file of the archive
|
||||
fs.writeFileSync(path.join(SNIPPETS_ARCHIVE_PATH, 'README.md'), output);
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During README generation for snippets archive: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`${green('SUCCESS!')} README file generated for snippets archive!`);
|
||||
console.timeEnd('Builder');
|
||||
}
|
||||
let snippets = {};
|
||||
// Setup everything
|
||||
let snippets = {},
|
||||
snippetsArray = [],
|
||||
startPart = '',
|
||||
endPart = '',
|
||||
output = '';
|
||||
const EMOJIS = {
|
||||
adapter: '🔌',
|
||||
array: '📚',
|
||||
@ -94,40 +52,47 @@ const EMOJIS = {
|
||||
utility: '🔧'
|
||||
};
|
||||
|
||||
let startPart = '',
|
||||
endPart = '',
|
||||
output = '',
|
||||
tagDbData = {};
|
||||
|
||||
console.time('Builder');
|
||||
|
||||
// Synchronously read all snippets from snippets folder and sort them as necessary (case-insensitive)
|
||||
snippets = util.readSnippets(SNIPPETS_PATH);
|
||||
snippetsArray = Object.keys(snippets).reduce((acc, key) => {
|
||||
acc.push(snippets[key]);
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
// Load static parts for the README file
|
||||
try {
|
||||
startPart = fs.readFileSync(path.join(STATIC_PARTS_PATH, 'README-start.md'), 'utf8');
|
||||
endPart = fs.readFileSync(path.join(STATIC_PARTS_PATH, 'README-end.md'), 'utf8');
|
||||
startPart = fs.readFileSync(
|
||||
path.join(STATIC_PARTS_PATH, 'README-start.md'),
|
||||
'utf8',
|
||||
);
|
||||
endPart = fs.readFileSync(
|
||||
path.join(STATIC_PARTS_PATH, 'README-end.md'),
|
||||
'utf8',
|
||||
);
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During static part loading: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Load tag data from the database
|
||||
tagDbData = util.readTags();
|
||||
console.log(tagDbData);
|
||||
|
||||
// Create the output for the README file
|
||||
try {
|
||||
const tags = util.prepTaggedData(tagDbData);
|
||||
const tags = util.prepTaggedData(
|
||||
Object.keys(snippets).reduce((acc, key) => {
|
||||
acc[key] = snippets[key].attributes.tags;
|
||||
return acc;
|
||||
}, {}),
|
||||
);
|
||||
|
||||
// Add the start static part
|
||||
output += `${startPart}\n`;
|
||||
|
||||
// Loop over tags and snippets to create the table of contents
|
||||
for (const tag of tags) {
|
||||
const capitalizedTag = util.capitalize(tag, true);
|
||||
const taggedSnippets = Object.entries(tagDbData).filter(v => v[1][0] === tag);
|
||||
const taggedSnippets = snippetsArray.filter(
|
||||
snippet => snippet.attributes.tags[0] === tag,
|
||||
);
|
||||
output += headers.h3((EMOJIS[tag] || '') + ' ' + capitalizedTag).trim();
|
||||
|
||||
output +=
|
||||
@ -135,32 +100,43 @@ try {
|
||||
'View contents',
|
||||
lists.ul(taggedSnippets, snippet =>
|
||||
misc.link(
|
||||
`\`${snippet[0]}\``,
|
||||
`${misc.anchor(snippet[0])}${snippet[1].includes('advanced') ? '-' : ''}`
|
||||
)
|
||||
)
|
||||
`\`${snippet.title}\``,
|
||||
`${misc.anchor(snippet.title)}${
|
||||
snippet.attributes.tags.includes('advanced') ? '-' : ''
|
||||
}`,
|
||||
),
|
||||
),
|
||||
) + '\n';
|
||||
}
|
||||
|
||||
// Loop over tags and snippets to create the list of snippets
|
||||
for (const tag of tags) {
|
||||
const capitalizedTag = util.capitalize(tag, true);
|
||||
const taggedSnippets = Object.entries(tagDbData).filter(v => v[1][0] === tag);
|
||||
const taggedSnippets = snippetsArray.filter(
|
||||
snippet => snippet.attributes.tags[0] === tag,
|
||||
);
|
||||
|
||||
output += misc.hr() + headers.h2((EMOJIS[tag] || '') + ' ' + capitalizedTag) + '\n';
|
||||
output +=
|
||||
misc.hr() + headers.h2((EMOJIS[tag] || '') + ' ' + capitalizedTag) + '\n';
|
||||
|
||||
for (const taggedSnippet of taggedSnippets) {
|
||||
let snippet = snippets[taggedSnippet[0] + '.md'];
|
||||
for (let snippet of taggedSnippets) {
|
||||
if (snippet.attributes.tags.includes('advanced'))
|
||||
output +=
|
||||
headers.h3(
|
||||
snippet.title + ' ' + misc.image('advanced', '/advanced.svg'),
|
||||
) + '\n';
|
||||
else output += headers.h3(snippet.title) + '\n';
|
||||
|
||||
// Add advanced tag
|
||||
if (taggedSnippet[1].includes('advanced')) {
|
||||
snippet = snippet.split(/\r?\n/);
|
||||
// add label to snippet title (first line)
|
||||
snippet[0] += ' ' + misc.image('advanced', '/advanced.svg');
|
||||
snippet = snippet.join('\n');
|
||||
}
|
||||
output += snippet.attributes.text;
|
||||
|
||||
output += makeExamples(snippet);
|
||||
output += `\`\`\`${config.language}\n${snippet.attributes.codeBlocks.es6}\n\`\`\``;
|
||||
|
||||
output += misc.collapsible(
|
||||
'Examples',
|
||||
`\`\`\`${config.language}\n${snippet.attributes.codeBlocks.example}\n\`\`\``,
|
||||
);
|
||||
|
||||
output +=
|
||||
'\n<br>' + misc.link('⬆ Back to top', misc.anchor('Contents')) + '\n';
|
||||
}
|
||||
}
|
||||
|
||||
@ -173,5 +149,104 @@ try {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`${green('SUCCESS!')} README file generated!`);
|
||||
// Snippets archive README file
|
||||
output = '';
|
||||
archivedSnippets = util.readSnippets(SNIPPETS_ARCHIVE_PATH);
|
||||
archivedSnippetsArray = Object.keys(archivedSnippets).reduce((acc, key) => {
|
||||
acc.push(archivedSnippets[key]);
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
// Load static parts for the README file
|
||||
try {
|
||||
startPart = fs.readFileSync(
|
||||
path.join(STATIC_PARTS_PATH, 'snippets_archive_README-start.md'),
|
||||
'utf8',
|
||||
);
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During static part loading: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Create the output for the README file
|
||||
try {
|
||||
output += `${startPart}\n`;
|
||||
|
||||
// Loop over tags and snippets to create the table of contents
|
||||
output += lists.ul(archivedSnippetsArray, snippet =>
|
||||
misc.link(
|
||||
`\`${snippet.title}\``,
|
||||
`${misc.anchor(snippet.title)}`,
|
||||
),
|
||||
);
|
||||
|
||||
for (let snippet of archivedSnippetsArray) {
|
||||
output += headers.h3(snippet.title) + '\n';
|
||||
|
||||
output += snippet.attributes.text;
|
||||
|
||||
output += `\`\`\`${config.language}\n${snippet.attributes.codeBlocks.es6}\n\`\`\``;
|
||||
|
||||
output += misc.collapsible(
|
||||
'Examples',
|
||||
`\`\`\`${config.language}\n${snippet.attributes.codeBlocks.example}\n\`\`\``,
|
||||
);
|
||||
|
||||
output +=
|
||||
'\n<br>' + misc.link('⬆ Back to top', misc.anchor('Contents')) + '\n';
|
||||
}
|
||||
// Write to the README file
|
||||
fs.writeFileSync(path.join(SNIPPETS_ARCHIVE_PATH, 'README.md'), output);
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During README generation: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Glossary README file
|
||||
output = '';
|
||||
glossarySnippets = util.readSnippets(GLOSSARY_PATH);
|
||||
glossarySnippetsArray = Object.keys(glossarySnippets).reduce((acc, key) => {
|
||||
acc.push(glossarySnippets[key]);
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
// Load static parts for the README file
|
||||
try {
|
||||
startPart = fs.readFileSync(
|
||||
path.join(STATIC_PARTS_PATH, 'glossary_README-start.md'),
|
||||
'utf8',
|
||||
);
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During static part loading: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Create the output for the README file
|
||||
try {
|
||||
output += `${startPart}\n`;
|
||||
|
||||
// Loop over tags and snippets to create the table of contents
|
||||
output += lists.ul(glossarySnippetsArray, snippet =>
|
||||
misc.link(
|
||||
`\`${snippet.title}\``,
|
||||
`${misc.anchor(snippet.title)}`,
|
||||
),
|
||||
);
|
||||
|
||||
for (let snippet of glossarySnippetsArray) {
|
||||
output += headers.h3(snippet.title) + '\n';
|
||||
|
||||
output += snippet.attributes.text;
|
||||
|
||||
output +=
|
||||
'\n<br>' + misc.link('⬆ Back to top', misc.anchor('Contents')) + '\n';
|
||||
}
|
||||
// Write to the README file
|
||||
fs.writeFileSync(path.join(GLOSSARY_PATH, 'README.md'), output);
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During README generation: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(`${green('SUCCESS!')} README files generated!`);
|
||||
console.timeEnd('Builder');
|
||||
@ -1,24 +0,0 @@
|
||||
/*
|
||||
This is the "keymaker" script that generates the glossary/keyword_database file.
|
||||
Run using `npm run glossary:keymaker`.
|
||||
*/
|
||||
|
||||
const fs = require('fs-extra');
|
||||
const { red } = require('kleur');
|
||||
const util = require('../util');
|
||||
|
||||
const glossaryFiles = util.getFilesInDir('./glossary', false);
|
||||
|
||||
try {
|
||||
const output =
|
||||
glossaryFiles.reduce(
|
||||
(accumulator, currentFilename) =>
|
||||
accumulator.toLowerCase().replace(/\.[^/.]+$/, '') +
|
||||
'\n' +
|
||||
currentFilename.toLowerCase().replace(/\.[^/.]+$/, '')
|
||||
) + '\n';
|
||||
fs.writeFileSync('glossary/keyword_database', output);
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During glossary keyword_database generation: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
@ -1,59 +0,0 @@
|
||||
/*
|
||||
This is the "librarian" script that generates the glossary/README file.
|
||||
Run using `npm run glossary:librarian`.
|
||||
*/
|
||||
|
||||
const fs = require('fs-extra');
|
||||
const { red } = require('kleur');
|
||||
const util = require('../util');
|
||||
|
||||
const glossaryFiles = util.getFilesInDir('./glossary', true, ['keyword_database', 'README.md']);
|
||||
const fileTitles = [];
|
||||
|
||||
const getGlossaryTermMarkdownBlock = fileName => {
|
||||
let fileContent = fs.readFileSync(fileName, 'utf8');
|
||||
|
||||
let title = fileContent
|
||||
.match(/###[^\n]*/)[0]
|
||||
.replace('### ', '')
|
||||
.trim();
|
||||
// let description = fileContent.replace(title, '').trim();
|
||||
fileTitles.push(title);
|
||||
|
||||
return fileContent.trim() + '\n';
|
||||
};
|
||||
|
||||
const glossaryFilesContentReducer = (accumulator, currentFilename) => {
|
||||
// handle first array item
|
||||
if (accumulator === glossaryFiles[0]) {
|
||||
return (
|
||||
getGlossaryTermMarkdownBlock(accumulator) +
|
||||
'\n' +
|
||||
getGlossaryTermMarkdownBlock(currentFilename)
|
||||
);
|
||||
}
|
||||
return accumulator + '\n' + getGlossaryTermMarkdownBlock(currentFilename);
|
||||
};
|
||||
|
||||
const getTermLinkMarkdownBlock = termTitle => {
|
||||
let anchor = util.getMarkDownAnchor(termTitle);
|
||||
return `* [\`${termTitle}\`](#${anchor})` + '\n';
|
||||
};
|
||||
|
||||
const glossaryTableOfContentsReducer = (accumulator, currentFile) => {
|
||||
if (accumulator === fileTitles[0])
|
||||
return getTermLinkMarkdownBlock(accumulator) + getTermLinkMarkdownBlock(currentFile);
|
||||
|
||||
return accumulator + getTermLinkMarkdownBlock(currentFile);
|
||||
};
|
||||
|
||||
try {
|
||||
const fileContents = glossaryFiles.reduce(glossaryFilesContentReducer);
|
||||
const TOC = '## Table of Contents\n\n' + fileTitles.reduce(glossaryTableOfContentsReducer);
|
||||
|
||||
const README = '# 30-seconds-of-code JavaScript Glossary\n\n' + TOC + '\n\n' + fileContents;
|
||||
fs.writeFileSync('glossary/README.md', README);
|
||||
} catch (err) {
|
||||
console.log(`${red('ERROR!')} During glossary README generation: ${err}`);
|
||||
process.exit(1);
|
||||
}
|
||||
@ -1,7 +1,456 @@
|
||||
---
|
||||
title: README
|
||||
tags:
|
||||
---
|
||||

|
||||
# Snippets Archive
|
||||
These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.
|
||||
## Contents
|
||||
|
||||
* [`binarySearch`](#binarysearch)
|
||||
* [`celsiusToFahrenheit`](#celsiustofahrenheit)
|
||||
* [`cleanObj`](#cleanobj)
|
||||
* [`collatz`](#collatz)
|
||||
* [`countVowels`](#countvowels)
|
||||
* [`factors`](#factors)
|
||||
* [`fahrenheitToCelsius`](#fahrenheittocelsius)
|
||||
* [`fibonacciCountUntilNum`](#fibonaccicountuntilnum)
|
||||
* [`fibonacciUntilNum`](#fibonacciuntilnum)
|
||||
* [`heronArea`](#heronarea)
|
||||
* [`howManyTimes`](#howmanytimes)
|
||||
* [`httpDelete`](#httpdelete)
|
||||
* [`httpPut`](#httpput)
|
||||
* [`isArmstrongNumber`](#isarmstrongnumber)
|
||||
* [`isSimilar`](#issimilar)
|
||||
* [`JSONToDate`](#jsontodate)
|
||||
* [`kmphToMph`](#kmphtomph)
|
||||
* [`levenshteinDistance`](#levenshteindistance)
|
||||
* [`mphToKmph`](#mphtokmph)
|
||||
* [`pipeLog`](#pipelog)
|
||||
* [`quickSort`](#quicksort)
|
||||
* [`removeVowels`](#removevowels)
|
||||
* [`solveRPN`](#solverpn)
|
||||
* [`speechSynthesis`](#speechsynthesis)
|
||||
* [`squareSum`](#squaresum)
|
||||
|
||||
### binarySearch
|
||||
|
||||
Use recursion. Similar to `Array.prototype.indexOf()` that finds the index of a value within an array.
|
||||
The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.prototype.indexOf()`.
|
||||
|
||||
Search a sorted array by repeatedly dividing the search interval in half.
|
||||
Begin with an interval covering the whole array.
|
||||
If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half.
|
||||
Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`.
|
||||
|
||||
```js
|
||||
const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
|
||||
if (start > end) return -1;
|
||||
const mid = Math.floor((start + end) / 2);
|
||||
if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);
|
||||
if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);
|
||||
return mid;
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2
|
||||
binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### celsiusToFahrenheit
|
||||
|
||||
Celsius to Fahrenheit temperature conversion.
|
||||
|
||||
Follows the conversion formula `F = 1.8C + 32`.
|
||||
|
||||
```js
|
||||
const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
celsiusToFahrenheit(33) // 91.4
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### cleanObj
|
||||
|
||||
Removes any properties except the ones specified from a JSON object.
|
||||
|
||||
Use `Object.keys()` method to loop over given JSON object and deleting keys that are not included in given array.
|
||||
If you pass a special key,`childIndicator`, it will search deeply apply the function to inner objects, too.
|
||||
|
||||
```js
|
||||
const cleanObj = (obj, keysToKeep = [], childIndicator) => {
|
||||
Object.keys(obj).forEach(key => {
|
||||
if (key === childIndicator) {
|
||||
cleanObj(obj[key], keysToKeep, childIndicator);
|
||||
} else if (!keysToKeep.includes(key)) {
|
||||
delete obj[key];
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };
|
||||
cleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### collatz
|
||||
|
||||
Applies the Collatz algorithm.
|
||||
|
||||
If `n` is even, return `n/2`. Otherwise, return `3n+1`.
|
||||
|
||||
```js
|
||||
const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
collatz(8); // 4
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### countVowels
|
||||
|
||||
Retuns `number` of vowels in provided string.
|
||||
|
||||
Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.
|
||||
|
||||
```js
|
||||
const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
countVowels('foobar'); // 3
|
||||
countVowels('gym'); // 0
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### factors
|
||||
|
||||
Returns the array of factors of the given `num`.
|
||||
If the second argument is set to `true` returns only the prime factors of `num`.
|
||||
If `num` is `1` or `0` returns an empty array.
|
||||
If `num` is less than `0` returns all the factors of `-int` together with their additive inverses.
|
||||
|
||||
Use `Array.from()`, `Array.prototype.map()` and `Array.prototype.filter()` to find all the factors of `num`.
|
||||
If given `num` is negative, use `Array.prototype.reduce()` to add the additive inverses to the array.
|
||||
Return all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.prototype.filter()`.
|
||||
Omit the second argument, `primes`, to return prime and non-prime factors by default.
|
||||
|
||||
**Note**:- _Negative numbers are not considered prime._
|
||||
|
||||
```js
|
||||
const factors = (num, primes = false) => {
|
||||
const isPrime = num => {
|
||||
const boundary = Math.floor(Math.sqrt(num));
|
||||
for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
|
||||
return num >= 2;
|
||||
};
|
||||
const isNeg = num < 0;
|
||||
num = isNeg ? -num : num;
|
||||
let array = Array.from({ length: num - 1 })
|
||||
.map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
|
||||
.filter(val => val);
|
||||
if (isNeg)
|
||||
array = array.reduce((acc, val) => {
|
||||
acc.push(val);
|
||||
acc.push(-val);
|
||||
return acc;
|
||||
}, []);
|
||||
return primes ? array.filter(isPrime) : array;
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
factors(12); // [2,3,4,6,12]
|
||||
factors(12, true); // [2,3]
|
||||
factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]
|
||||
factors(-12, true); // [2,3]
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### fahrenheitToCelsius
|
||||
|
||||
Fahrenheit to Celsius temperature conversion.
|
||||
|
||||
Follows the conversion formula `C = (F - 32) * 5/9`.
|
||||
|
||||
```js
|
||||
const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
fahrenheitToCelsius(32); // 0
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### fibonacciCountUntilNum
|
||||
|
||||
Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive).
|
||||
|
||||
Use a mathematical formula to calculate the number of fibonacci numbers until `num`.
|
||||
|
||||
```js
|
||||
const fibonacciCountUntilNum = num =>
|
||||
Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
fibonacciCountUntilNum(10); // 7
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### fibonacciUntilNum
|
||||
|
||||
Generates an array, containing the Fibonacci sequence, up until the nth term.
|
||||
|
||||
Create an empty array of the specific length, initializing the first two values (`0` and `1`).
|
||||
Use `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||
Uses a mathematical formula to calculate the length of the array required.
|
||||
|
||||
```js
|
||||
const fibonacciUntilNum = num => {
|
||||
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
||||
return Array.from({ length: n }).reduce(
|
||||
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
|
||||
[]
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### heronArea
|
||||
|
||||
Returns the area of a triangle using only the 3 side lengths, Heron's formula. Assumes that the sides define a valid triangle. Does NOT assume it is a right triangle.
|
||||
|
||||
More information on what Heron's formula is and why it works available here: https://en.wikipedia.org/wiki/Heron%27s_formula.
|
||||
|
||||
Uses `Math.sqrt()` to find the square root of a value.
|
||||
|
||||
```js
|
||||
const heronArea = (side_a, side_b, side_c) => {
|
||||
const p = (side_a + side_b + side_c) / 2
|
||||
return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
heronArea(3, 4, 5); // 6
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### howManyTimes
|
||||
|
||||
Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.
|
||||
Works for both negative and positive integers.
|
||||
|
||||
If `divisor` is `-1` or `1` return `Infinity`.
|
||||
If `divisor` is `-0` or `0` return `0`.
|
||||
Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer.
|
||||
Return the number of times the loop was executed, `i`.
|
||||
|
||||
```js
|
||||
const howManyTimes = (num, divisor) => {
|
||||
if (divisor === 1 || divisor === -1) return Infinity;
|
||||
if (divisor === 0) return 0;
|
||||
let i = 0;
|
||||
while (Number.isInteger(num / divisor)) {
|
||||
i++;
|
||||
num = num / divisor;
|
||||
}
|
||||
return i;
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
howManyTimes(100, 2); // 2
|
||||
howManyTimes(100, 2.5); // 2
|
||||
howManyTimes(100, 0); // 0
|
||||
howManyTimes(100, -1); // Infinity
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### httpDelete
|
||||
|
||||
Makes a `DELETE` request to the passed URL.
|
||||
|
||||
Use `XMLHttpRequest` web api to make a `delete` request to the given `url`.
|
||||
Handle the `onload` event, by running the provided `callback` function.
|
||||
Handle the `onerror` event, by running the provided `err` function.
|
||||
Omit the third argument, `err` to log the request to the console's error stream by default.
|
||||
|
||||
```js
|
||||
const httpDelete = (url, callback, err = console.error) => {
|
||||
const request = new XMLHttpRequest();
|
||||
request.open('DELETE', url, true);
|
||||
request.onload = () => callback(request);
|
||||
request.onerror = () => err(request);
|
||||
request.send();
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
httpDelete('https://website.com/users/123', request => {
|
||||
console.log(request.responseText);
|
||||
}); // 'Deletes a user from the database'
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### httpPut
|
||||
|
||||
Makes a `PUT` request to the passed URL.
|
||||
|
||||
Use `XMLHttpRequest` web api to make a `put` request to the given `url`.
|
||||
Set the value of an `HTTP` request header with `setRequestHeader` method.
|
||||
Handle the `onload` event, by running the provided `callback` function.
|
||||
Handle the `onerror` event, by running the provided `err` function.
|
||||
Omit the last argument, `err` to log the request to the console's error stream by default.
|
||||
|
||||
```js
|
||||
const httpPut = (url, data, callback, err = console.error) => {
|
||||
const request = new XMLHttpRequest();
|
||||
request.open("PUT", url, true);
|
||||
request.setRequestHeader('Content-type','application/json; charset=utf-8');
|
||||
request.onload = () => callback(request);
|
||||
request.onerror = () => err(request);
|
||||
request.send(data);
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
const password = "fooBaz";
|
||||
const data = JSON.stringify(password);
|
||||
httpPut('https://website.com/users/123', data, request => {
|
||||
console.log(request.responseText);
|
||||
}); // 'Updates a user's password in database'
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### isArmstrongNumber
|
||||
|
||||
Checks if the given number is an Armstrong number or not.
|
||||
|
||||
Convert the given number into an array of digits. Use the exponent operator (`**`) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.
|
||||
|
||||
```js
|
||||
const isArmstrongNumber = digits =>
|
||||
(arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
|
||||
(digits + '').split('')
|
||||
);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
isArmstrongNumber(1634); // true
|
||||
isArmstrongNumber(56); // false
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### isSimilar
|
||||
|
||||
Determines if the `pattern` matches with `str`.
|
||||
|
||||
Use `String.toLowerCase()` to convert both strings to lowercase, then loop through `str` and determine if it contains all characters of `pattern` and in the correct order.
|
||||
Adapted from [here](https://github.com/forrestthewoods/lib_fts/blob/80f3f8c52db53428247e741b9efe2cde9667050c/code/fts_fuzzy_match.js#L18).
|
||||
|
||||
```js
|
||||
const isSimilar = (pattern, str) =>
|
||||
[...str].reduce(
|
||||
(matchIndex, char) =>
|
||||
char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()
|
||||
? matchIndex + 1
|
||||
: matchIndex,
|
||||
0
|
||||
) === pattern.length;
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
isSimilar('rt','Rohit'); // true
|
||||
isSimilar('tr','Rohit'); // false
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### JSONToDate
|
||||
|
||||
Converts a JSON object to a date.
|
||||
|
||||
@ -14,6 +463,271 @@ const JSONToDate = arr => {
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
JSONToDate(/Date(1489525200000)/); // "14/3/2017"
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### kmphToMph
|
||||
|
||||
Convert kilometers/hour to miles/hour.
|
||||
|
||||
Multiply the constant of proportionality with the argument.
|
||||
|
||||
```js
|
||||
const kmphToMph = (kmph) => 0.621371192 * kmph;
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
kmphToMph(10); // 16.09344000614692
|
||||
kmphToMph(345.4); // 138.24264965280207
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### levenshteinDistance
|
||||
|
||||
Calculates the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between two strings.
|
||||
|
||||
Calculates the number of changes (substitutions, deletions or additions) required to convert `string1` to `string2`.
|
||||
Can also be used to compare two strings as shown in the second example.
|
||||
|
||||
```js
|
||||
const levenshteinDistance = (string1, string2) => {
|
||||
if (string1.length === 0) return string2.length;
|
||||
if (string2.length === 0) return string1.length;
|
||||
let matrix = Array(string2.length + 1)
|
||||
.fill(0)
|
||||
.map((x, i) => [i]);
|
||||
matrix[0] = Array(string1.length + 1)
|
||||
.fill(0)
|
||||
.map((x, i) => i);
|
||||
for (let i = 1; i <= string2.length; i++) {
|
||||
for (let j = 1; j <= string1.length; j++) {
|
||||
if (string2[i - 1] === string1[j - 1]) {
|
||||
matrix[i][j] = matrix[i - 1][j - 1];
|
||||
} else {
|
||||
matrix[i][j] = Math.min(
|
||||
matrix[i - 1][j - 1] + 1,
|
||||
matrix[i][j - 1] + 1,
|
||||
matrix[i - 1][j] + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return matrix[string2.length][string1.length];
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7
|
||||
const compareStrings = (string1,string2) => (100 - levenshteinDistance(string1,string2) / Math.max(string1.length,string2.length));
|
||||
compareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### mphToKmph
|
||||
|
||||
Convert miles/hour to kilometers/hour.
|
||||
|
||||
Multiply the constant of proportionality with the argument.
|
||||
|
||||
```js
|
||||
const mphToKmph = (mph) => 1.6093440006146922 * mph;
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
mphToKmph(10); // 16.09344000614692
|
||||
mphToKmph(85.9); // 138.24264965280207
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### pipeLog
|
||||
|
||||
Logs a value and returns it.
|
||||
|
||||
Use `console.log` to log the supplied value, combined with the `||` operator to return it.
|
||||
|
||||
```js
|
||||
const pipeLog = data => console.log(data) || data;
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
pipeLog(1); // logs `1` and returns `1`
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### quickSort
|
||||
|
||||
QuickSort an Array (ascending sort by default).
|
||||
|
||||
Use recursion.
|
||||
Use `Array.prototype.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it.
|
||||
If the parameter `desc` is truthy, return array sorts in descending order.
|
||||
|
||||
```js
|
||||
const quickSort = ([n, ...nums], desc) =>
|
||||
isNaN(n)
|
||||
? []
|
||||
: [
|
||||
...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),
|
||||
n,
|
||||
...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
|
||||
];
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
quickSort([4, 1, 3, 2]); // [1,2,3,4]
|
||||
quickSort([4, 1, 3, 2], true); // [4,3,2,1]
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### removeVowels
|
||||
|
||||
Returns all the vowels in a `str` replaced by `repl`.
|
||||
|
||||
Use `String.prototype.replace()` with a regexp to replace all vowels in `str`.
|
||||
Omot `repl` to use a default value of `''`.
|
||||
|
||||
```js
|
||||
const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
removeVowels("foobAr"); // "fbr"
|
||||
removeVowels("foobAr","*"); // "f**b*r"
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### solveRPN
|
||||
|
||||
Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).
|
||||
Throws appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators.
|
||||
|
||||
Use a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.
|
||||
Use `String.prototype.replace()` with a regular expression to replace `^` with `**`, `String.prototype.split()` to tokenize the string and `Array.prototype.filter()` to remove empty tokens.
|
||||
Use `Array.prototype.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.
|
||||
Numeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.
|
||||
|
||||
```js
|
||||
const solveRPN = rpn => {
|
||||
const OPERATORS = {
|
||||
'*': (a, b) => a * b,
|
||||
'+': (a, b) => a + b,
|
||||
'-': (a, b) => a - b,
|
||||
'/': (a, b) => a / b,
|
||||
'**': (a, b) => a ** b
|
||||
};
|
||||
const [stack, solve] = [
|
||||
[],
|
||||
rpn
|
||||
.replace(/\^/g, '**')
|
||||
.split(/\s+/g)
|
||||
.filter(el => !/\s+/.test(el) && el !== '')
|
||||
];
|
||||
solve.forEach(symbol => {
|
||||
if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {
|
||||
stack.push(symbol);
|
||||
} else if (Object.keys(OPERATORS).includes(symbol)) {
|
||||
const [a, b] = [stack.pop(), stack.pop()];
|
||||
stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));
|
||||
} else {
|
||||
throw `${symbol} is not a recognized symbol`;
|
||||
}
|
||||
});
|
||||
if (stack.length === 1) return stack.pop();
|
||||
else throw `${rpn} is not a proper RPN. Please check it and try again`;
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
|
||||
solveRPN('2 3 ^'); // 8
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### speechSynthesis
|
||||
|
||||
Performs speech synthesis (experimental).
|
||||
|
||||
Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.
|
||||
Use `window.speechSynthesis.speak()` to play the message.
|
||||
|
||||
Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance).
|
||||
|
||||
```js
|
||||
const speechSynthesis = message => {
|
||||
const msg = new SpeechSynthesisUtterance(message);
|
||||
msg.voice = window.speechSynthesis.getVoices()[0];
|
||||
window.speechSynthesis.speak(msg);
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
speechSynthesis('Hello, World'); // // plays the message
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
### squareSum
|
||||
|
||||
Squares each number in an array and then sums the results together.
|
||||
|
||||
Use `Array.prototype.reduce()` in combination with `Math.pow()` to iterate over numbers and sum their squares into an accumulator.
|
||||
|
||||
```js
|
||||
const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
squareSum(1, 2, 2); // 9
|
||||
```
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#contents)
|
||||
|
||||
3
src/static-parts/glossary_README-start.md
Normal file
3
src/static-parts/glossary_README-start.md
Normal file
@ -0,0 +1,3 @@
|
||||
# 30-seconds-of-code JavaScript Glossary
|
||||
|
||||
## Contents
|
||||
4
src/static-parts/snippets_archive_README-start.md
Normal file
4
src/static-parts/snippets_archive_README-start.md
Normal file
@ -0,0 +1,4 @@
|
||||

|
||||
# Snippets Archive
|
||||
These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.
|
||||
## Contents
|
||||
Reference in New Issue
Block a user