` element (menu) or an ` ` element, of type button, checkbox or radio.
10 |
11 | **Note**: On Mac, elements that aren't text input elements tend not to get focus assigned to them.
12 |
13 | Typically a user can press the tab key to move the focus around the page among focusable elements, and use the space bar to activate it (press a button, choose a radio).
14 |
15 | Do not confuse focus with a selection over the document, consisting mostly of static text nodes. See `window.getSelection()` for that.
16 |
17 | When there is no selection, the active element is the page's `` or `null`.
18 |
--------------------------------------------------------------------------------
/javascript/problems/tracePolygon.md:
--------------------------------------------------------------------------------
1 | Point in Polygon
2 |
3 | ### The problem
4 |
5 | You're going write a function called pointInPoly to test if a point is inside a polygon.
6 |
7 | Points will be represented as [x,y] arrays.
8 |
9 | The polygon will be an array of points which are the polygon's vertices. The last point in the array connects back to the first point.
10 |
11 | You can assume:
12 |
13 | The polygon will be a valid simple polygon. That is, it will have at least three points, none of its edges will cross each other, and exactly two edges will meet at each vertex.
14 | In the tests, the point will never fall exactly on an edge of the polygon.
15 |
16 |
17 | ### Solution
18 |
19 | ```js
20 | //Return true if point is inside poly, and false if it is not
21 | function pointInPoly(poly, point) {
22 | let num = poly.length
23 | let i = 0
24 | let j = num - 1
25 | let c = false
26 | for (i=0; i < num; i++) {
27 | if (
28 | (poly[i][1] > point[1]) != (poly[j][1] > point[1]) &&
29 | (point[0] < (poly[j][0] - poly[i][0]) * (point[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0])
30 | ) {
31 | c = !c
32 | }
33 | j = i
34 | }
35 | return c
36 | }
37 | ```
38 |
--------------------------------------------------------------------------------
/javascript/problems/defaultArguments.md:
--------------------------------------------------------------------------------
1 | ## Task
2 |
3 | Write a function `defaultArguments`. It takes a function as an argument, along with an object containing default values for that function's arguments, and returns another function which defaults to the right values.
4 |
5 | You cannot assume that the function's arguments have any particular names.
6 |
7 | You should be able to call `defaultArguments` repeatedly to change the defaults.
8 |
9 | ```js
10 | function add(a, b) { return a + b; };
11 |
12 | var add_ = defaultArguments(add, { b: 9 });
13 | add_(10); // returns 19
14 | add_(10,7); // returns 17
15 | add_(); // returns NaN
16 |
17 | add_ = defaultArguments(add_, { b:3, a:2 });
18 | add_(10); // returns 13 now
19 | add_(); // returns 5
20 |
21 | add_ = defaultArguments(add_, { c:3 }); // doesn't do anything, since c isn't an argument
22 | add_(10); // returns NaN
23 | add_(10,10); // returns 20
24 | ```
25 |
26 | ## Solution
27 |
28 | ```js
29 | function defaultArguments(f, params) {
30 | const defaults = f.toString().match(/\(([^)]*)\)/)[1].split(',').map(name =>
31 | params[name.replace(/\/\*[\s\S]*?\*\/|([^:]|^)\/\/.*$/gm, '').trim()]
32 | )
33 |
34 | const res = (...args) => f(...args, ...defaults.slice(args.length))
35 | res.toString = () => f.toString()
36 | return res
37 | }
38 | ```
39 |
--------------------------------------------------------------------------------
/javascript/callbacksVsPromises.md:
--------------------------------------------------------------------------------
1 | ## What are the pros and cons of using Promises instead of callbacks?
2 |
3 | It is fair to say promises are just syntactic sugar. Everything you can do with promises you can do with callbacks. In fact, most promise implementations provide ways of converting between the two whenever you want.
4 |
5 | The deep reason why promises are often better is that they're more **composeable**, which roughly means that combining multiple promises "just works", while combining multiple callbacks often doesn't. For instance, it's trivial to assign a promise to a variable and attach additional handlers to it later on, or even attach a handler to a large group of promises that gets executed only after all the promises resolve. While you can sort of emulate these things with callbacks, it takes a lot more code, is very hard to do correctly, and the end result is usually far less maintainable.
6 |
7 | One of the biggest (and subtlest) ways promises gain their composability is by uniform handling of return values and uncaught exceptions. With callbacks, how an exception gets handled may depend entirely on which of the many nested callbacks threw it, and which of the functions taking callbacks has a try/catch in its implementation. With promises, you know that an exception which escapes one callback function will be caught and passed to the error handler you provided with `.catch()`.
8 |
--------------------------------------------------------------------------------
/javascript/problems/lcs.md:
--------------------------------------------------------------------------------
1 | ## Write a function called LCS that accepts two sequences, and returns the longest subsequence common to the passed in sequences.
2 |
3 | ### Subsequence
4 |
5 | A subsequence is different from a substring. The terms of a subsequence need not be consecutive terms of the original sequence.
6 |
7 | ### Example subsequence
8 |
9 | Subsequences of "abc" = "a", "b", "c", "ab", "ac", "bc"
10 |
11 | ### LCS examples
12 |
13 | ```
14 | LCS( "abcdef" , "abc" ) => returns "abc"
15 | LCS( "abcdef" , "acf" ) => returns "acf"
16 | LCS( "132535365" , "123456789" ) => returns "12356"
17 | ```
18 |
19 | ### Notes
20 |
21 | * Both arguments will be strings
22 | * Return value must be a string
23 | * Return an empty string if there exists no common subsequence
24 | * Both arguments will have one or more characters
25 | * All tests will only have a single longest common subsequence. Don't worry about cases such as LCS( "1234", "3412" ), which would have two possible longest common subsequences: "12" and "34".
26 |
27 | ## Solution
28 |
29 | ```js
30 | function LCS(x, y) {
31 | if (x.length === 0 || y.length === 0) {
32 | return ''
33 | }
34 | if (x[0] === y[0]) {
35 | return x[0].concat(LCS(x.slice(1), y.slice(1)))
36 | }
37 | const lcsLeft = LCS(x.slice(1), y)
38 | const lcsRight = LCS(x, y.slice(1))
39 | return lcsLeft.length > lcsRight.length ? lcsLeft : lcsRight
40 | }
41 | ```
42 |
--------------------------------------------------------------------------------
/javascript/problems/fizzBuzz.md:
--------------------------------------------------------------------------------
1 | ## Task
2 |
3 | Write a program that prints all the numbers from 1 to 100. For multiples of 3, instead of the number, print "Fizz", for multiples of 5 print "Buzz". For numbers which are multiples of both 3 and 5, print "FizzBuzz".
4 |
5 | ## Solution
6 |
7 | ```js
8 | for (var i = 1; i <= 100; i++) {
9 | var f = i % 3 == 0, b = i % 5 == 0;
10 | console.log(f ? b ? "FizzBuzz" : "Fizz" : b ? "Buzz" : i);
11 | }
12 |
13 | // one liner
14 | [...Array(15).keys()].map(i => console.log((++i % 3 ? '' : 'fizz') + (i % 5 ? '' : 'buzz') || i))
15 |
16 | // in 53 chars
17 | for(x=0;x++<100;)console.log(x%3||"fizz",x%5||"buzz")
18 |
19 |
20 | // generator
21 | function * fizzBuzz() {
22 | var i = 0;
23 | while (true) {
24 | ++i;
25 | var x = 0;
26 | if (i % 3 === 0 && i % 5 === 0) yield 'Fizz Buzz';
27 | else if (i % 3 === 0) yield 'Fizz';
28 | else if (i % 5 === 0) yield 'Buzz';
29 | else yield i;
30 | }
31 |
32 | }
33 |
34 | var gen = fizzBuzz();
35 | for (var i = 0; i < 100; i++) {
36 | console.log(gen.next().value + ' ');
37 | }
38 |
39 |
40 | // Fast
41 | console.log(
42 | Array.apply(null, {length: 100}).map(function(val, index) {
43 | index++;
44 | if (index % 15 == 0){return "FizzBuzz";}
45 | if (index % 3 == 0){return "Fizz";}
46 | if (index % 5 == 0){return "Buzz";}
47 | return index;
48 | }).join('\n')
49 | );
50 | ```
51 |
--------------------------------------------------------------------------------
/javascript/toPrimitive.md:
--------------------------------------------------------------------------------
1 | ## What is `toPrimitive`?
2 |
3 | The `Symbol.toPrimitive `is a symbol that specifies a function valued property that is called to convert an object to a corresponding primitive value.
4 |
5 | Property attributes of Symbol.toPrimitive
6 | * Writable no
7 | * Enumerable no
8 | * Configurable no
9 |
10 | With the help of the Symbol.toPrimitive property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument hint, which specifies the preferred type of the result primitive value. The hint argument can be one of "number", "string", and "default".
11 |
12 | Following example describes how Symbol.toPrimitive property can modify the primitive value converted from an object.
13 |
14 | ```js
15 | // An object without Symbol.toPrimitive property.
16 | var obj1 = {};
17 | console.log(+obj1); // NaN
18 | console.log(`${obj1}`); // "[object Object]"
19 | console.log(obj1 + ""); // "[object Object]"
20 |
21 | // An object with Symbol.toPrimitive property.
22 | var obj2 = {
23 | [Symbol.toPrimitive](hint) {
24 | if (hint == "number") {
25 | return 10;
26 | }
27 | if (hint == "string") {
28 | return "hello";
29 | }
30 | return true;
31 | }
32 | };
33 | console.log(+obj2); // 10 -- hint is "number"
34 | console.log(`${obj2}`); // "hello" -- hint is "string"
35 | console.log(obj2 + ""); // "true" -- hint is "default"
36 | ```
37 |
--------------------------------------------------------------------------------
/javascript/problems/validBraces.md:
--------------------------------------------------------------------------------
1 | ## Task
2 |
3 | Write a function called `validBraces` that takes a string of braces, and determines if the order of the braces is valid. `validBraces` should return true if the string is valid, and false if it's invalid.
4 |
5 | This Kata is similar to the Valid Parentheses Kata, but introduces four new characters. Open and closed brackets, and open and closed curly braces. Thanks to @arnedag for the idea!
6 |
7 | All input strings will be nonempty, and will only consist of open parentheses '(' , closed parentheses ')', open brackets '[', closed brackets ']', open curly braces '{' and closed curly braces '}'.
8 |
9 | **What is considered Valid?** A string of braces is considered valid if all braces are matched with the correct brace.
10 | For example:
11 | '(){}[]' and '([{}])' would be considered valid, while '(}', '[(])', and '[({})](]' would be considered invalid.
12 |
13 | Examples:
14 | ```js
15 | validBraces( "(){}[]" ) // returns true
16 | validBraces( "(}" ) // returns false
17 | validBraces( "[(])" ) // returns false
18 | validBraces( "([{}])" ) // returns true
19 | ```
20 |
21 | ## Solution
22 |
23 | ```js
24 | function validBraces(braces){
25 | const order = '(){}[]'
26 | const stack = []
27 |
28 | braces.split('').forEach(brace => {
29 | if (!stack.length || stack[stack.length - 1] !== order[order.indexOf(brace) - 1]) {
30 | stack.push(brace)
31 | } else {
32 | stack.pop()
33 | }
34 | })
35 |
36 | return !stack.length
37 | }
38 | ```
39 |
--------------------------------------------------------------------------------
/javascript/hostAndNativeObjects.md:
--------------------------------------------------------------------------------
1 | ## What's the difference between host objects and native objects?
2 |
3 | __Native object__ is an object in an ECMAScript implementation whose semantics are fully defined by this specification rather than by the host environment.
4 |
5 | Standard native objects are defined in the specification.
6 | Some native objects are built-in; others may be constructed during the course of execution of an ECMAScript program.
7 |
8 | __Host object__ is an object supplied by the host environment to complete the execution environment of ECMAScript.
9 |
10 | There are some of them: `window, document, location, history, XMLHttpRequest, setTimeout, getElementsByTagName, querySelectorAll, ...`
11 |
12 | Any object that is not native is a host object.
13 |
14 | ### ES6
15 | Also, worthwhile noting that ES6 does not use the terminology native and host objects any more.
16 | Instead, it defines below object types, with more clear explanations of their intended behaviour.
17 |
18 | * Ordinary object
19 | — object that has the default behaviour for the essential internal methods that must be supported by all objects
20 |
21 | * Exotic object
22 | — object that does not have the default behaviour for one or more of the essential internal methods that must be supported by all objects NOTE Any object that is not an ordinary object is an exotic object.
23 |
24 | * Standard object
25 | — object whose semantics are defined by the specification
26 |
27 | * Built-in object
28 | — object specified and supplied by an ECMAScript implementation
29 |
--------------------------------------------------------------------------------
/javascript/longPolling.md:
--------------------------------------------------------------------------------
1 | ## Long polling
2 |
3 | As soon as an event occurs, the server sends back the response in the suspended request and closes it, exactly like you close the output stream of a servlet response. The client then consumes the response and opens a new long-lived Ajax request to the server.
4 |
5 | ### Client side
6 |
7 | ```js
8 | function longPolling() {
9 | $.getJSON('ajax', function(events) {
10 | processEvents(events)
11 | longPolling()
12 | })
13 | }
14 | longPolling()
15 | ```
16 |
17 |
18 | ### Server side
19 |
20 | ```js
21 | function respondToClient(res, session, cnt = 0) {
22 | //context: res is the object we use to respond to the client
23 | //session: just some info about the client, irrelevant here
24 |
25 | //nothing to tell the client, let's long poll.
26 | if (nothingToSend(res, session)) {
27 | if (cnt < MAX_LONG_POLL_TIME) {
28 | //call this function in 100 ms, increase the counter
29 | setTimeout(function(){
30 | respondToClient(request_id, res, session, cnt + 1)
31 | }, 100)
32 | } else {
33 | closeConnection(res)
34 | //Counter too high.
35 | //we have nothing to send and we kept the connection for too long,
36 | //close it. The client will open another.
37 | }
38 | } else {
39 | sendWhatWeHave(res)
40 | closeConnection(res)
41 | //the client will consume the data we sent,
42 | //then quickly send another request.
43 | }
44 | }
45 | ```
46 |
--------------------------------------------------------------------------------
/databases/having.md:
--------------------------------------------------------------------------------
1 | ## What does `HAVING` does in SQL?
2 |
3 | Specifies a search condition for a group or an aggregate. `HAVING` can be used only with the `SELECT` statement. `HAVING` is typically used in a `GROUP BY` clause. When `GROUP BY` is not used, `HAVING` behaves like a `WHERE` clause.
4 |
5 | ### The semantics of Having
6 |
7 | To better understand having, you need to see it from a theoretical point of view.
8 |
9 | A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by).
10 |
11 | The `HAVING` is simply equivalent to a `WHERE` clause after the group by has executed and before the select part of the query is computed.
12 |
13 | Lets say your query is:
14 |
15 | ```sql
16 | select a, b, count(*)
17 | from Table
18 | where c > 100
19 | group by a, b
20 | having count(*) > 10;
21 | ```
22 |
23 | The evaluation of this query can be seen as the following steps:
24 |
25 | Perform the `WHERE`, eliminating rows that do not satisfy it.
26 | Group the table into subsets based upon the values of a and b (each tuple in each subset has the same values of a and b).
27 | Eliminate subsets that do not satisfy the HAVING condition
28 | Process each subset outputting the values as indicated in the `SELECT` part of the query. This creates one output tuple per subset left after step 3.
29 | You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).
30 |
--------------------------------------------------------------------------------
/javascript/attributeVsProperty.md:
--------------------------------------------------------------------------------
1 | ## What's the difference between an "attribute" and a "property"?
2 | ### Attribute
3 | 1. Attributes are defined by HTML, all definitions inside HTML tag are attributes.
4 | 2. The type of attributes is always string.
5 |
6 | ### Property
7 | 1. Properties belong to DOM, the nature of DOM is an object in JavaScript. We can get and set properties as we do to a normal object in JavaScript and properties can be any types.
8 | 2. Non-custom attributes have 1:1 mapping onto properties, like: `id`, `class`, `title`, etc.
9 | 3. Non-custom property (attribute) changes when corresponding attribute (property) changes in most cases.
10 | 4. Attribute which has a default value doesn't change when corresponding property changes.
11 |
12 | ### Best Practice
13 |
14 | It is recommended to use properties in JavaScript as it's much easier and faster. Especially for boolean type attributes like: `checked`, `disabled` and `selected`, browser automatically converts them into boolean type properties.
15 |
16 | ```html
17 |
18 | ```
19 |
20 | #### Good practice
21 |
22 | ```js
23 | // get id
24 | document.getElementById('test').id;
25 | // set class
26 | document.getElementById('test').className = 'red';
27 | // get and set radio control status
28 | document.getElementById('test').checked;
29 | document.getElementById('test').checked = true;
30 | ```
31 |
32 | #### Bad practice
33 |
34 | ```js
35 | // get id
36 | document.getElementById('test').getAttribute('id');
37 | // set class
38 | document.getElementById('test').setAttribute('class', 'red');
39 | ```
40 |
--------------------------------------------------------------------------------
/javascript/functionDeclarations.md:
--------------------------------------------------------------------------------
1 | ## Anonymous vs. referenced vs. declared functions
2 |
3 | ### Anonymous
4 |
5 | Anonymous functions are typically used as callbacks.
6 |
7 | ```js
8 | function takesACallback(callback) {
9 | // do some interesting things here
10 | return "The callback says: " + callback();
11 | }
12 |
13 | takesACallback(function() {
14 | return "I'm the callback!";
15 | }); // returns "The callback says: I'm the callback!"
16 | ```
17 | See the function that’s a parameter to the takesACallback call? Notice that it doesn’t have a name? That’s an anonymous function.
18 |
19 | ### Referenced
20 | However, you can still have a reference to an anonymous function, just because it is unnamed it doesn’t mean it’s unreferenced.
21 | Also it's called function expression.
22 | ```js
23 | var reference = function() {
24 | return "I'm still an anonymous function";
25 | }
26 |
27 | reference(); // returns "I'm still an anonymous function"
28 | ```
29 | The function itself is still anonymous (it doesn’t have a name directly attached to it), but you can call the function by the named reference. Function expressions are not hoisted like function declarations decribed below.
30 |
31 | ### Declared
32 | Declared functions are not anonymous. They have a name directly attached to the function, with no need for a named reference.
33 | ```js
34 | function declared() {
35 | return "I'm not anonymous function";
36 | }
37 |
38 | declared(); // returns "I'm not anonymous function"
39 | ```
40 | Writing a named function like this results in a function declaration which if hoisted to the top of the file.
41 |
42 |
--------------------------------------------------------------------------------
/javascript/useStrict.md:
--------------------------------------------------------------------------------
1 | ## What is "use strict";? what are the advantages and disadvantages to using it?
2 |
3 | If you put "use strict"; at the top of your code (or function), then the JS is evaluated in strict mode. Strict mode throws more errors and disables some features in an effort to make your code more robust, readable, and accurate.
4 |
5 | Advantages
6 |
7 | Taken from John Resig:
8 |
9 | Strict mode helps out in a couple ways:
10 |
11 | It catches some common coding bloopers, throwing exceptions.
12 | It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).
13 | It disables features that are confusing or poorly thought out.
14 | Sounds great! I've been reading JavaScript: the Good Parts, and it seems there are a number of “features that are confusing or poorly thought out.” I'll take anything that helps me avoid them!
15 |
16 | Disadvantages
17 |
18 | I had a harder time finding why people don’t like strict mode. The best explanation I found was when code mixed strict and “normal” modes. If a developer used a library that was in strict mode, but the developer was used to working in normal mode, they might call some actions on the library that wouldn’t work as expected. Worse, since the developer is in normal mode, they don’t have the advantages of extra errors being thrown, so the error might fail silently.
19 |
20 | Also, as listed above, strict mode stops you from doing certain things. People generally think that you shouldn’t use those things in the first place, but some developers don’t like the constraint and want to use all the features of the language.
21 |
--------------------------------------------------------------------------------
/javascript/hoisting.md:
--------------------------------------------------------------------------------
1 | ## Explain "hoisting"
2 | All declarations, both variables and functions, are processed first, before any part of your code is executed.
3 |
4 | When you see `var a = 2`, you probably think of that as one statement.
5 | But JavaScript actually thinks of it as two statements:
6 | `var a` and `a = 2`.
7 |
8 | The first statement, the declaration, is processed during the compilation phase.
9 | The second statement, the assignment, is left in place for the execution phase.
10 | Declarations themselves are hoisted, but assignments, even assignments of function expressions, are not hoisted.
11 | What this leads to is that all declarations in a scope, regardless of where they appear,
12 | are processed first before the code itself is executed.
13 |
14 | Functions are hoisted first, and then variables.
15 | Function declarations are hoisted, but function expressions are not.
16 |
17 | While multiple/duplicate `var` declarations are effectively ignored,
18 | subsequent function declarations do override previous ones.
19 |
20 | ```js
21 | foo(); // "b"
22 |
23 | var a = true;
24 | if (a) {
25 | function foo() { console.log( "a" ); }
26 | }
27 | else {
28 | function foo() { console.log( "b" ); }
29 | }
30 | ```
31 |
32 | In ECMAScript 2015, `let` will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
33 |
34 | ```js
35 | function do_something() {
36 | console.log(foo); // ReferenceError
37 | let foo = 2;
38 | }
39 | ```
40 |
--------------------------------------------------------------------------------
/javascript/void.md:
--------------------------------------------------------------------------------
1 | ## What does `void` do?
2 |
3 | The void operator evaluates the given expression and then returns undefined.
4 |
5 | ### Description
6 | This operator allows inserting expressions that produce side effects into places where an expression that evaluates to undefined is desired.
7 |
8 | The `void` operator is often used merely to obtain the undefined primitive value, usually using `void(0)` (which is equivalent to `void 0`). In these cases, the global variable undefined can be used instead (assuming it has not been assigned to a non-default value).
9 |
10 | ### Immediately Invoked Function Expressions
11 | When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration.
12 |
13 | ```js
14 | void function iife() {
15 | var bar = function () {};
16 | var baz = function () {};
17 | var foo = function () {
18 | bar();
19 | baz();
20 | };
21 | var biz = function () {};
22 |
23 | foo();
24 | biz();
25 | }();
26 | ```
27 |
28 | JavaScript URIs
29 | When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined. The void operator can be used to return undefined. For example:
30 |
31 | ```js
32 |
33 | Click here to do nothing
34 |
35 |
36 |
37 | Click here for green background
38 |
39 | ```
40 |
41 | Note, however, that the `javascript:` pseudo protocol is discouraged over other alternatives, such as unobtrusive event handlers.
42 |
--------------------------------------------------------------------------------
/javascript/SPAvsSEO.md:
--------------------------------------------------------------------------------
1 | ## Explain what a single page app is and how to make one SEO-friendly.
2 |
3 | SPA stands for Single-Page Application. When a page is loaded, you can browse other links and load new content without the need of a full page reload. Only one piece of the page is discarded and replaced by the content of the next page. With this, you will avoid requesting all JavaScript and CSS files again and rendering your header and footer HTML.
4 |
5 | If you believe that being googleable is enough for your website, then you don't need to modify anything. Since Googlebots will execute your JavaScript, your page contents and links will be available for them.
6 |
7 | However, Google recognizes that some JavaScript code may not be executed if its too complex or arcane. So, what you can do to help Google (and every crawler), is to add a Sitemap file named sitemap.xml at your web server root directory to tell crawlers what links do you have in your website. You can also include "invisible links", like the ones that just appears after you fill a form. You can also check [how google sees your page](https://www.google.com/webmasters/tools/googlebot-fetch).
8 |
9 | *Note:* if you want your site to be correctly rendered in Facebook's preview or Twitter's cards, then you need to pre-render your pages. In this case, being just googleable is not enough. Another problem is that Google may index your content without parsing variables. For example, you can see things like {{ myVar }} in search results instead of the actual content.
10 |
11 | For crawlers that aren't able to execute JavaScript code, you need to pre-render the page and make it available for them. Also, the Sitemap should be referencing those pre-rendered pages for an extra help.
12 |
--------------------------------------------------------------------------------
/javascript/proxyLeak.md:
--------------------------------------------------------------------------------
1 | ## How `WeakMap` can help you prevent memory leaks?
2 |
3 | The experienced JavaScript programmer will notice that this API could be implemented in JavaScript with two arrays (one for keys, one for values) shared by the four API methods. Such an implementation would have two main inconveniences. The first one is an O(n) search (n being the number of keys in the map). The second one is a memory leak issue. With manually written maps, the array of keys would keep references to key objects, preventing them from being garbage collected. In native WeakMaps, references to key objects are held "weakly", which means that they do not prevent garbage collection in case there would be no other reference to the object.
4 |
5 | Because of references being weak, WeakMap keys are not enumerable (i.e. there is no method giving you a list of the keys). If they were, the list would depend on the state of garbage collection, introducing non-determinism. If you want to have a list of keys, you should use a Map.
6 |
7 | ```js
8 | const privateData = new WeakMap()
9 |
10 | class MyClass {
11 | constructor(name, age) {
12 | privateData(this, { name, age })
13 | }
14 |
15 | getName() {
16 | return privateData.get(this).name;
17 | }
18 |
19 | getAge() {
20 | return privateData.get(this).age;
21 | }
22 | }
23 |
24 | export default MyClass
25 | ```
26 |
27 | ```js
28 | const myElement = document.getElementById('logo')
29 | const myWeakmap = new WeakMap()
30 |
31 | myWeakmap.set(myElement, {timesClicked: 0})
32 |
33 | myElement.addEventListener('click', () => {
34 | const logoData = myWeakmap.get(myElement)
35 | logoData.timesClicked++
36 |
37 | myWeakmap.set(myElement, logoData)
38 | }, false)
39 | ```
40 |
--------------------------------------------------------------------------------
/css/marginCollapsing.md:
--------------------------------------------------------------------------------
1 | ## Explain what is margin collapsing
2 |
3 | Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.
4 |
5 | Margin collapsing occurs in three basic cases:
6 |
7 | 1. Adjacent siblings
8 |
9 | The margins of adjacent siblings are collapsed (except when the later sibling needs to be cleared past floats). For example:
10 | ```html
11 | The bottom margin of this paragraph is collapsed...
12 | ...with the top margin of this paragraph.
13 | ```
14 | 2. Parent and first/last child
15 |
16 | If there is no border, padding, inline content, or clearance to separate the margin-top of a block from the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.
17 | 3. Empty blocks
18 |
19 | If there is no border, padding, inline content, height, or min-height to separate a block's margin-top from its margin-bottom, then its top and bottom margins collapse.
20 |
21 | More complex margin collapsing (of more than two margins) occurs when these cases are combined.
22 |
23 | These rules apply even to margins that are zero, so the margin of a first/last child ends up outside its parent (according to the rules above) whether or not the parent's margin is zero.
24 |
25 | When negative margins are involved, the size of the collapsed margin is the sum of the largest positive margin and the smallest (most negative) negative margin.
26 |
27 | Margins of floating and absolutely positioned elements never collapse.
28 |
--------------------------------------------------------------------------------
/javascript/problems/foldAnArray.md:
--------------------------------------------------------------------------------
1 | # Literally fold an array
2 |
3 | ## Task
4 |
5 | Write a method that folds a given array of integers by the middle x-times.
6 |
7 | ```js
8 | Fold 1-times:
9 | [1,2,3,4,5] -> [6,6,3]
10 |
11 | A little visualization (NOT for the algorithm but for the idea of folding):
12 |
13 | Step 1 Step 2 Step 3 Step 4 Step5
14 | 5/ 5| 5\
15 | 4/ 4| 4\
16 | 1 2 3 4 5 1 2 3/ 1 2 3| 1 2 3\ 6 6 3
17 | ----*---- ----* ----* ----* ----*
18 |
19 |
20 | Fold 2-times:
21 | [1,2,3,4,5] -> [9,6]
22 | ```
23 |
24 | As you see, if the count of numbers is odd, the middle number will stay. Otherwise the fold-point is between the middle-numbers, so all numbers would be added in a way.
25 |
26 | The array will always contain numbers and will never be null. The parameter runs will always be a positive integer greater than 0 and says how many runs of folding your method has to do.
27 |
28 | If an array with one element is folded, it stays as the same array.
29 |
30 | The input array should not be modified!
31 |
32 | ## Solution
33 |
34 | ```js
35 | function foldArray(array, runs)
36 | {
37 | if (runs === 0 || array.length === 1) return array
38 | const m = array.length / 2
39 | return foldArray(
40 | array
41 | .slice(0, m)
42 | .map((x, i) => x + array[array.length - i - 1])
43 | .concat(array.slice(m, Math.ceil(m))),
44 | runs - 1
45 | )
46 | }
47 | ```
48 |
49 | ## Shortest
50 | ```js
51 | function foldArray(a, n) {
52 | const r = [], c = a.slice();
53 | while (c.length) r.push(c.pop() + (c.shift() || 0));
54 | return n - 1 ? foldArray(r, n - 1) : r;
55 | }
56 | ```
57 |
--------------------------------------------------------------------------------
/javascript/browserRender.md:
--------------------------------------------------------------------------------
1 | ## How browser renders the web page?
2 |
3 | 
4 |
5 | - **JavaScript**. Typically JavaScript is used to handle work that will result in visual changes, whether it’s jQuery’s animate function, sorting a data set, or adding DOM elements to the page. It doesn’t have to be JavaScript that triggers a visual change, though: CSS Animations, Transitions, and the Web Animations API are also commonly used.
6 | - **Style calculations**. This is the process of figuring out which CSS rules apply to which elements based on matching selectors, for example, .headline or .nav > .nav__item. From there, once rules are known, they are applied and the final styles for each element are calculated.
7 | - **Layout**. Once the browser knows which rules apply to an element it can begin to calculate how much space it takes up and where it is on screen. The web’s layout model means that one element can affect others, for example the width of the element typically affects its children’s widths and so on all the way up and down the tree, so the process can be quite involved for the browser.
8 | - **Paint**. Painting is the process of filling in pixels. It involves drawing out text, colors, images, borders, and shadows, essentially every visual part of the elements. The drawing is typically done onto multiple surfaces, often called layers.
9 | - **Compositing**. Since the parts of the page were drawn into potentially multiple layers they need to be drawn to the screen in the correct order so that the page renders correctly. This is especially important for elements that overlap another, since a mistake could result in one element appearing over the top of another incorrectly.
10 |
11 | 
12 |
--------------------------------------------------------------------------------
/network/README.md:
--------------------------------------------------------------------------------
1 | # Network Q&As
2 |
3 | ## Traditionally, why has it been better to serve site assets from multiple domains?
4 |
5 | Web browsers are restricted to download several items per host at once,
6 | so the more resources hosted on external domains you use the faster a page loads.
7 | Old IEs permitted only 2 request, modern browsers allow 6 — 8 requests,
8 | but there are still reasons to use this aproach.
9 |
10 | If your server’s domain set a cookie on the client,
11 | that client will send the cookie on every request it makes to your domain,
12 | including those requests for static assets.
13 |
14 | But each new domain you reference has the upfront cost of a DNS lookup,
15 | so you have to be sure that it’s actually going to be worth it.
16 | If you are a small site then serving assets from a subdomain will likely not be worth it;
17 | the browser can probably fetch several under-parallelised assets from one domain quicker
18 | than it can perform DNS lookups across multiple domains and parallelise those.
19 | You can still use `dns-prefetch` though.
20 |
21 | ## What is Hyper Text Transfer Protocol
22 |
23 | Hypertext Transfer Protocol (HTTP) is a networking protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web.
24 |
25 | ## What is HTTP session?
26 |
27 | HTTP session is a sequence of network request-response transactions. An HTTP client initiates a request. It establishes a Transmission Control Protocol (TCP) connection to a particular port on a host (typically port 80; see List of TCP and UDP port numbers). An HTTP server listening on that port waits for a client's request message. Upon receiving the request, the server sends back a status line, such as "HTTP/1.1 200 OK", and a message of its own, the body of which is perhaps the requested resource, an error message, or some other information.
28 |
--------------------------------------------------------------------------------
/javascript/references.md:
--------------------------------------------------------------------------------
1 | ## Why is (0,obj.prop)() not a method call?
2 |
3 | Or what's the difference between:
4 | ```js
5 | obj.prop()
6 | (0, obj.prop)()
7 | ```
8 |
9 | The difference is in the call context. Consider the following examples:
10 | ```js
11 | 'use strict'
12 |
13 | const obj = {
14 | getThis() {
15 | return this
16 | },
17 | }
18 |
19 | obj.getThis() === obj // true
20 |
21 | const f = obj.getThis
22 | f() // undefined
23 | ```
24 |
25 | Same thing applies for a comma operator:
26 | ```js
27 | (expr1, expr2) === expr2
28 | ```
29 |
30 | That is, both expressions are evaluated, the result of the whole expression is expr2.
31 |
32 | ```js
33 | (0, obj.getThis)() // undefined
34 | ```
35 |
36 | We are now ready to understand the examples we looked at earlier.
37 |
38 | The following expression produces a reference:
39 |
40 | ```js
41 | obj.getThis
42 | ```
43 |
44 | If you wrap obj.getThis in parentheses, nothing changes, parentheses only syntactically group things, but the don’t influence how something is evaluated. That is, the result of the following expression is still a reference:
45 | ```js
46 | (obj.getThis)
47 | ```
48 | If, however, you assign the reference returned by obj.getThis to a variable, the reference is dereferenced:
49 | ```js
50 | const func = obj.getThis
51 | ```
52 | In other words: what is stored in func is a function, not a reference.
53 | The comma operator also dereferences its operands. Consider this expression:
54 |
55 | ```js
56 | (0, obj.getThis)
57 | ```
58 |
59 | That's why Babel use `(0, referenceFunction)()` syntax.
60 | It uses the comma operator to avoid function calls being transpiled to method calls.
61 | ```js
62 | import { func } from 'library'
63 |
64 | func()
65 | ```
66 | Babel compiles it to this ES5 code:
67 |
68 | ```js
69 | 'use strict';
70 |
71 | var _library = require('library');
72 | (0, _library.func)(); // (A)
73 | ```
74 |
--------------------------------------------------------------------------------
/javascript/problems/sumOfIntervals.md:
--------------------------------------------------------------------------------
1 | ### Description
2 |
3 | Write a function called `sumIntervals` that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once.
4 |
5 | #### Intervals
6 |
7 | Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4.
8 |
9 | #### Overlapping Intervals
10 |
11 | List containing overlapping intervals:
12 |
13 | ```js
14 | [
15 | [1,4],
16 | [7, 10],
17 | [3, 5]
18 | ]
19 | ```
20 | The sum of the lengths of these intervals is `7`. Since `[1, 4]` and `[3, 5]` overlap, we can treat the interval as `[1, 5]`, which has a length of `4`.
21 |
22 | #### Examples:
23 |
24 | ```js
25 | sumIntervals( [
26 | [1,2],
27 | [6, 10],
28 | [11, 15]
29 | ] ); //=> returns 9
30 |
31 | sumIntervals( [
32 | [1,4],
33 | [7, 10],
34 | [3, 5]
35 | ] ); //=> returns 7
36 |
37 | sumIntervals( [
38 | [1,5],
39 | [10, 20],
40 | [1, 6],
41 | [16, 19],
42 | [5, 11]
43 | ] ); //=> returns 19
44 | ```
45 |
46 | ### Solution
47 |
48 | ```js
49 | }
50 | function sumIntervals(intervals){
51 | return intervals
52 | .sort(
53 | (a, b) => a[0] > b[0] ? 1 : -1
54 | ).reduce(
55 | (ar, i) => {
56 | if (ar.length && ar[ar.length - 1][1] >= i[0]) {
57 | ar[ar.length - 1][1] = Math.max(i[1], ar[ar.length - 1][1])
58 | return ar
59 | } else {
60 | ar.push(i)
61 | return ar
62 | }
63 | }, []
64 | ).reduce(
65 | (sum, i) => (sum + i[1] - i[0]), 0
66 | )
67 | }
68 | ```
69 |
70 | ### Sly solution
71 |
72 | ```js
73 | function sumIntervals(intervals){
74 | return Object.keys(intervals.reduce(function(hash, interval) {
75 | for(var i = interval[0]; i < interval[1]; i++) hash[i] = 1;
76 | return hash;
77 | }, {})).length;
78 | }
79 | ```
80 |
--------------------------------------------------------------------------------
/javascript/reflow.md:
--------------------------------------------------------------------------------
1 | ## What is browser reflow?
2 |
3 | Reflow is the name of the web browser process for re-calculating the positions and geometries of elements in the document, for the purpose of re-rendering part or all of the document. Because reflow is a user-blocking operation in the browser, it is useful for developers to understand how to improve reflow time and also to understand the effects of various document properties (DOM depth, CSS rule efficiency, different types of style changes) on reflow time. Sometimes reflowing a single element in the document may require reflowing its parent elements and also any elements which follow it.
4 |
5 | Reflow occurs when you:
6 |
7 | insert, remove or update an element in the DOM
8 | modify content on the page, e.g. the text in an input box
9 | move a DOM element
10 | animate a DOM element
11 | take measurements of an element such as offsetHeight or getComputedStyle
12 | change a CSS style
13 | change the className of an element
14 | add or remove a stylesheet
15 | resize the window
16 | scroll
17 |
18 | Guidelines
19 |
20 | Here are some easy guidelines to help you minimize reflow in your web pages:
21 |
22 | - Reduce unnecessary DOM depth. Changes at one level in the DOM tree can cause changes at every level of the tree - all the way up to the root, and all the the way down into the children of the modified node. This leads to more time being spent performing reflow.
23 | - Minimize CSS rules, and remove unused CSS rules.
24 | - If you make complex rendering changes such as animations, do so out of the flow. Use position-absolute or position-fixed to accomplish this.
25 | - Avoid unnecessary complex CSS selectors - descendant selectors in particular - which require more CPU power to do selector matching.
26 |
27 | Trigger only compositor properties:
28 |
29 | - Stick to transform and opacity changes for your animations.
30 | - Promote moving elements with will-change or translateZ.
31 | - Avoid overusing promotion rules; layers require memory and management.
32 |
--------------------------------------------------------------------------------
/javascript/problems/float2bin.md:
--------------------------------------------------------------------------------
1 | ## Implement a function called `float2bin` that converts a float number to the corresponding `32-bit` binary value. This involves analysing each part of the input number and appointing each bit of the output accordingly.
2 |
3 | ### Rules:
4 |
5 | * The conversion should match the IEEE754 Single precision 32-bit technical standard.
6 | * The implementation should be able to handle both Strings ("123", "1.23") and Numbers (123, 1.23) as input.
7 | * It should convert both positive and negative numbers.
8 | * The output should always be a 32 characters long string, so padding of 0's is necessary if input is not negative.
9 | * The point of this kata is to teach how floats are build on a binary level, so typed arrays are disabled.
10 |
11 | ### Ugly solution
12 |
13 | ```js
14 | var float2bin = function(input) {
15 | const sign = input < 0 ? '1' : '0'
16 | input = Math.abs(input)
17 | const num = parseFloat(input).toString(2)
18 | const int = parseFloat(~~input).toString(2)
19 | const prefract = parseFloat(input % 1).toString(2).replace('0.','')
20 | const exp = parseFloat(127 + (~~input ? int.length - 1 : -prefract.indexOf(1) - 1)).toString(2)
21 | const fract = ~~input ?
22 | prefract :
23 | prefract.slice(prefract.indexOf(1), prefract.indexOf(1) + 22)
24 | const padding = 32 - 8 - (int.length || 0) - ((int == '0' ? fract.length - 1 : fract.length) || 0)
25 |
26 | return sign
27 | .concat('0'.repeat(8 - exp.length))
28 | .concat(exp)
29 | .concat(((int == '0' ? '' : int).concat(fract)).slice(1))
30 | .concat('0'.repeat(padding > 0 ? padding : 0))
31 | .slice(0, 32)
32 | }
33 | ```
34 |
35 | ### Shorter solution
36 |
37 | ```js
38 | var float2bin = function(input) {
39 | var
40 | n0 = +input,
41 | n = Math.abs(n0),
42 | e = Math.floor(Math.log(n) / Math.LN2),
43 | f = n * Math.pow(2, 23 - e) & ~(1 << 23);
44 | return (n0 >= 0 ? "0" : "1") +
45 | ("00000000" + (e + 127).toString(2)).slice(-8) +
46 | ("00000000000000000000000" + f.toString(2)).slice(-23);
47 | }
48 | ```
49 |
--------------------------------------------------------------------------------
/javascript/checkArray.md:
--------------------------------------------------------------------------------
1 | ## How do you check if an object is an array or not?
2 |
3 | The best way to find out whether or not an object is an instance of a particular class is to use the toString method from Object.prototype:
4 |
5 | ```js
6 | var arrayList = [1,2,3];
7 | ```
8 | One of the best use cases of type-checking an object is when we do method overloading in JavaScript. For example, let's say we have a method called greet, which takes one single string and also a list of strings. To make our greet method workable in both situations, we need to know what kind of parameter is being passed. Is it a single value or a list of values?
9 |
10 | ```js
11 | function greet(param){
12 | if(){ // here have to check whether param is array or not
13 | }else{
14 | }
15 | }
16 | ```
17 | However, as the implementation above might not necessarily check the type for arrays, we can check for a single value string and put some array logic code in the else block. For example:
18 |
19 | ```js
20 | function greet(param){
21 | if(typeof param === 'string'){
22 | }else{
23 | // If param is of type array then this block of code would execute
24 | }
25 | }
26 | ```
27 | Now it's fine we can go with either of the aforementioned two implementations, but when we have a situation where the parameter can be single value, array, and object type, we will be in trouble.
28 |
29 | Coming back to checking the type of an object, as mentioned previously we can use Object.prototype.toString
30 |
31 | ```js
32 | if( Object.prototype.toString.call( arrayList ) === '[object Array]' ) {
33 | console.log('Array!');
34 | }
35 | ```
36 | If you are using jQuery, then you can also use the jQuery isArray method:
37 |
38 | ```js
39 | if($.isArray(arrayList)){
40 | console.log('Array');
41 | }else{
42 | console.log('Not an array');
43 | }
44 | ```
45 | FYI, jQuery uses Object.prototype.toString.call internally to check whether an object is an array or not.
46 |
47 | In modern browsers, you can also use
48 |
49 | ```js
50 | Array.isArray(arrayList);
51 | ```
52 |
53 | Array.isArray is supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5
54 |
--------------------------------------------------------------------------------
/javascript/eventDelegation.md:
--------------------------------------------------------------------------------
1 | ## What is event delegation?
2 |
3 | Event delegation allows you to avoid adding event listeners to specific nodes. Instead, the event listener is added to one parent. That event listener analyzes bubbled events to find a match on child elements.
4 |
5 | Event delegation makes use of two features of JavaScript events: *event bubbling* and the *target element*. When an event is triggered on an element, the same event is also triggered on all of that element’s ancestors. This process is known as event bubbling; the event bubbles up from the originating element to the top of the DOM tree. The original target element of any event is stored in a property of the event object - `event.target`. Using event delegation it’s possible to add an event handler to a parent element, wait for an event to bubble up from a child element and easily determine from which element the event originated.
6 |
7 | ```js
8 | function handleMenuItemClick(e = window.event) {
9 | const target = e.target || e.srcElement
10 |
11 | if (target.tagName.toLowerCase() === 'li') {
12 | // do stuff...
13 | }
14 | }
15 |
16 | document.getElementById('menu').addEventListener('click', handleMenuItemClick)
17 | ```
18 |
19 | Pros:
20 |
21 | - There are less event handlers to setup and reside in memory. This is the big one; better performance and less crashing.
22 | - There’s no need to re-attach handlers after a DOM update. If your page content is generated dynamically you don’t need to add and remove event handlers as elements are loaded or unloaded.
23 |
24 | Cons:
25 |
26 | - There’s a risk your event management code could become a performance bottleneck, so keep it as lean as possible.
27 | - Not all events bubble. The `blur`, `focus`, `load` and `unload` events don’t bubble like other events. The blur and focus events can actually be accessed using the capturing phase (in browsers other than IE) instead of the bubbling phase but that’s a story for another day.
28 | - You need caution when managing some mouse events. If your code is handling the mousemove event you are in serious risk of creating a performance bottleneck because the mousemove event is triggered so often.
29 |
--------------------------------------------------------------------------------
/common/functionalVsUnit.md:
--------------------------------------------------------------------------------
1 | What is the difference between functional and unit tests?
2 |
3 | Unit Testing is a subtype of Functional Testing.
4 | 
5 |
6 | * A unit test tests an independent unit of behavior. What is a unit of behavior? It's the smallest piece of the system that can be independently unit tested. (This definition is actually circular, IOW it's really not a definition at all, but it seems to work quite well in practice, because you can sort-of understand it intuitively.)
7 | * A functional test tests an independent piece of functionality.
8 | --
9 | * A unit of behavior is very small: while I absolutely dislike this stupid "one unit test per method" mantra, from a size perspective it is about right. A unit of behavior is something between a part of a method and maybe a couple of methods. At most an object, but not more than one.
10 | * A piece of functionality usually comprises many methods and cuts across several objects and often through multiple architectural layers.
11 | --
12 | * A unit test would be something like: when I call the `validate_country_code()` function and pass it the country code 'ZZ' it should return false.
13 | * A functional test would be: when I fill out the shipping form with a country code of ZZ, I should be redirected to a help page which allows me to pick my country code out of a menu.
14 | --
15 | * Unit tests are written by developers, for developers, from the developer's perspective.
16 | * Functional tests may be user facing, in which case they are written by developers together with users (or maybe with the right tools and right users even by the users themselves), for users, from the user's perspective. Or they may be developer facing (e.g. when they describe some internal piece of functionality that the user doesn't care about), in which case they are written by developers, for developers, but still from the user's perspective.
17 | --
18 | * In the former case, the functional tests may also serve as acceptance tests and as an executable encoding of functional requirements or a functional specification, in the latter case, they may also serve as integration tests.
19 | * Unit tests change frequently, functional tests should never change within a major release.
20 |
--------------------------------------------------------------------------------
/javascript/problems/di.md:
--------------------------------------------------------------------------------
1 | ## Implement Dependency Injection
2 |
3 | Did you hear about Dependency Injection pattern? The main idea of this pattern is that you may have ability to pass dependencies into your function in any order and they will be resolved automatically. Take a look at this:
4 |
5 | ```js
6 | var myDependentFunc = inject(function (secondDepency, firstDependency) {
7 | firstDependency();
8 | secondDepency();
9 | });
10 |
11 | myDependentFunc();
12 | ```
13 |
14 | As you can see we just put some variables into the function's signature and work with them as usualy. But we know nothing about where these variables are located! Let's assume that all dependencies are stored in the single hash object (for instanse 'deps') and the injector function will be sought among 'deps' properties:
15 |
16 | ```js
17 | var deps = {
18 | 'firstDependency': function () {return 'this is firstDependency';},
19 | 'secondDepency': function () {return 'this is secondDepency';},
20 | };
21 | ```
22 |
23 | Ok, I hope this is clear. Also, in order to setup DependencyInjector (DI) we need to specify dependency object:
24 |
25 | ```js
26 | var DI = function (dependency) {
27 | this.dependency = dependency;
28 | };
29 | ```
30 |
31 | Your task is create `DI.prototype.inject` method that will return a new function with resolved dependencies. And don't forget about nested functions. You shouldn't handle them.
32 |
33 | ### Solution
34 |
35 | ```js
36 | var DI = function (dependency) {
37 | this.dependency = dependency;
38 | };
39 |
40 | // Should return new function with resolved dependencies
41 | DI.prototype.inject = function (func) {
42 | const STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
43 | const ARGUMENT_NAMES = /([^\s,]+)/g;
44 | function getParamNames(func) {
45 | return (func + '')
46 | .replace(/[/][/].*$/mg,'') // strip single-line comments
47 | .replace(/\s+/g, '') // strip white space
48 | .replace(/[/][*][^/*]*[*][/]/g, '') // strip multi-line comments
49 | .split('){', 1)[0].replace(/^[^(]*[(]/, '') // extract the parameters
50 | .replace(/=[^,]+/g, '') // strip any ES6 defaults
51 | .split(',').filter(Boolean); // split & filter [""]
52 | }
53 | const ps = getParamNames(func).map(a=>this.dependency[a])
54 | return function(){
55 | return func.apply(this, ps)
56 | }
57 | }
58 | ```
59 |
--------------------------------------------------------------------------------
/javascript/ajax.md:
--------------------------------------------------------------------------------
1 | ## Explain AJAX in as much detail as possible
2 |
3 | AJAX stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including JSON, XML, HTML, and even text files. AJAX’s most appealing characteristic, however, is its "asynchronous" nature, which means it can do all of this without having to refresh the page. This lets you update portions of a page based upon user events.
4 |
5 | The two major features of AJAX allow you to do the following:
6 |
7 | - Make requests to the server without reloading the page
8 | - Receive and work with data from the server
9 |
10 | ### How it works
11 |
12 | 1. A user interaction in the browser triggers the event, such as a button click
13 |
14 | 2. The AJAX call fires. This creates and AJAX request, browsers use the XMLHttpRequest object. When the server responds to the browser’s request, the same XMLHttpRequest object will process the result.
15 |
16 | 3. The server-side script receives the input from JavaScript, and processes the data.
17 |
18 | 4. After the data is processed, the script sends the data back to the original client-side page that made the request via XML
19 |
20 | 5. Once the data is received, a second JavaScript callback function, is called this function captures the data, and updates the web page accordingly.
21 |
22 | ```html
23 |
24 | Make a request
25 |
26 |
55 | ```
56 |
--------------------------------------------------------------------------------
/javascript/problems/minerPath.md:
--------------------------------------------------------------------------------
1 | ## Task
2 |
3 | A poor miner is trapped in a mine and you have to help him to get out !
4 |
5 | Only, the mine is all dark so you have to tell him where to go.
6 |
7 | In this kata, you will have to implement a method solve(map, miner, exit) that has to return the path the miner must take to reach the exit as an array of moves, such as : ['up', 'down', 'right', 'left']. There are 4 possible moves, up, down, left and right, no diagonal.
8 |
9 | map is a 2-dimensional array of boolean values, representing squares. false for walls, true for open squares (where the miner can walk). It will never be larger than 5 x 5. It is laid out as an array of columns. All columns will always be the same size, though not necessarily the same size as rows (in other words, maps can be rectangular). The map will never contain any loop, so there will always be only one possible path. The map may contain dead-ends though.
10 |
11 | miner is the position of the miner at the start, as an object made of two zero-based integer properties, x and y. For example {x:0, y:0} would be the top-left corner.
12 |
13 | exit is the position of the exit, in the same format as miner.
14 |
15 | Note that the miner can't go outside the map, as it is a tunnel.
16 |
17 | Let's take a pretty basic example:
18 |
19 | ```js
20 | var map = [[true, false],
21 | [true, true]];
22 |
23 | solve(map, {x:0,y:0}, {x:1,y:1});
24 | // Should return ['right', 'down']
25 | ```
26 | These rows are inverted so actually matrix from the example above looks like:
27 | ```
28 | |true, true|
29 | |false, true|
30 | ```
31 |
32 | Why? :(
33 |
34 | ## Solution
35 |
36 | ```js
37 | // I will pretify it after the call :)
38 | function solve(map, { x, y }, exit, res = [], visited = {}) {
39 | visited[`${x}${y}`] = true
40 | if (x === exit.x && y === exit.y) {
41 | return res
42 | }
43 | const possibleMoves = {
44 | right: [x + 1, y],
45 | left: [x - 1, y],
46 | up: [x, y - 1],
47 | down: [x, y + 1],
48 | }
49 |
50 | return Object.keys(possibleMoves).map(move => {
51 | const [newX, newY] = possibleMoves[move]
52 |
53 | if (map[newX] && map[newX][newY] && !visited[`${newX}${newY}`]) {
54 | const updatedRes = res.slice()
55 | updatedRes.push(move)
56 | return solve(map, { x: newX, y: newY }, exit, updatedRes, visited)
57 | }
58 | }).filter(path => path).sort((a, b) => - a.length + b.length)[0]
59 | }
60 | ```
61 |
--------------------------------------------------------------------------------
/javascript/syncVsAsyncFunctions.md:
--------------------------------------------------------------------------------
1 | ## Explain the difference between synchronous and asynchronous functions.
2 |
3 | Let's say you have two functions, `foo` and `bar`, which are executing synchronously:
4 |
5 | ```js
6 | function foo() {
7 | var returnValue = bar();
8 | console.log(returnValue);
9 | }
10 |
11 | function bar() {
12 | return "bar";
13 | }
14 | ```
15 |
16 | In order to make the API "asynchronous" is to change it to use callbacks:
17 |
18 | ```js
19 | function foo() {
20 | bar(function(returnValue) {
21 | console.log(returnValue);
22 | });
23 | }
24 |
25 | function bar(callback) {
26 | callback("bar");
27 | }
28 | ```
29 |
30 | But the fact of the matter is, this code is still entirely synchronous. The callback is being executed on the same call stack, and no threading optimizations are being made, no scalability benefits are to be had.
31 |
32 | It then becomes a question of code readability and coding style. I personally find the typical `var val = func();` type code more readable and readily understandable. The only drawback is, that if you one day would need to change the functionality of bar so, that it would need to perform some I/O activity or call some other function which is asynchronous, you need to change the API of bar as well.
33 |
34 | My personal preference: use traditional, synchronous patterns when applicable. Always use asynchronous style when I/O is involved or when in doubt.
35 |
36 | It is very important for APIs to be either 100% synchronous or 100% asynchronous. Consider this example:
37 |
38 | ```js
39 | // WARNING! DO NOT USE! BAD UNSAFE HAZARD!
40 | function maybeSync(arg, cb) {
41 | if (arg) {
42 | cb();
43 | return;
44 | }
45 |
46 | fs.stat('file', cb);
47 | }
48 | ```
49 |
50 | This API is hazardous because in the following case:
51 |
52 | ```js
53 | maybeSync(true, () => {
54 | foo();
55 | });
56 | bar();
57 | ```
58 |
59 | It is not clear whether foo() or bar() will be called first.
60 |
61 | The following approach is much better:
62 |
63 | ```js
64 | function definitelyAsync(arg, cb) {
65 | if (arg) {
66 | process.nextTick(cb);
67 | return;
68 | }
69 |
70 | fs.stat('file', cb);
71 | }
72 | ```
73 |
74 | Note: the next tick queue is completely drained on each pass of the event loop before additional I/O is processed. As a result, recursively setting nextTick callbacks will block any I/O from happening, just like a while(true); loop.
75 |
--------------------------------------------------------------------------------
/javascript/proxyVsGetters.md:
--------------------------------------------------------------------------------
1 | ## What is the pros and cons of using `Proxy` vs Getters and Setters?
2 |
3 | Getters and setters interception can be implemented with ES5 property accessors (getter/setter) instead of ES6 `Proxies`. Many popular libraries use this technique, for example `MobX` and `Vue`. Using proxies over accessors has two main advantages and a major disadvantage.
4 |
5 | ### Expando properties
6 |
7 | Expando properties are dynamically added properties in JavaScript. The ES5 technique does not support expando properties since accessors have to be predefined per property to be able to intercept operations. This is a technical reason why central stores with a predefined set of keys are trending nowadays.
8 |
9 | On the other hand, the `Proxy` technique does support expando properties, since proxies are defined per object and they intercept operations for every property of the object.
10 |
11 | A typical example where expando properties are crucial is with using arrays. JavaScript arrays are pretty much useless without the ability to add or remove items from them. ES5 data binding techniques usually hack around this problem by providing custom or overwritten Array methods.
12 |
13 | ### Getters and setters
14 |
15 | Libraries using the ES5 method provide 'computed' bound properties by some special syntax. These properties have their native equivalents, namely getters and setters. However the ES5 method uses getters/setters internally to set up the data binding logic, so it can not work with property accessors.
16 |
17 | Proxies intercept every kind of property access and mutation, including getters and setters, so this does not pose a problem for the ES6 method.
18 |
19 | ### Browser support
20 |
21 | The big disadvantage of using Proxies is browser support. They are only supported in the most recent browsers and the best parts of the Proxy API are non polyfillable. Also their performance is not optimized yet.
22 |
23 | ### Proxy wrapper
24 |
25 | ES6 Proxies can only create a separate "copy" of the original object, but this copy will fail in cases where you try to compare them with `===:`
26 |
27 | ```js
28 | var obj = { a: 1 }
29 | var proxy = new Proxy(obj, handlers)
30 |
31 | obj === proxy // false
32 | ```
33 |
34 | This introduces more complexity when you are accessing nested properties - you will always need to be careful about whether a value you retrieved is the "real one" or just a proxy, otherwise it can lead to obscure bugs when you rely on `===` comparators.
35 |
--------------------------------------------------------------------------------
/javascript/comet.md:
--------------------------------------------------------------------------------
1 | ## What are the ways server can push data to the client?
2 |
3 | ### Comet
4 |
5 | Traditionally, the __Comet__ term (coinded in 2006 by Alex Russell) has been referring to both HTTP Streaming and HTTP Polling. But consider that the first implementations of HTTP Streaming go back to 2000, well before the Comet term was coined.
6 |
7 | __Comet__ is a set of technology principles/communication patterns that are typically implemented using HTTP long-poll. It enables a server to send data to the browser on demand (i.e. server push). Current comet implementations require some complex Javascript on the client side and support from the server-side (for long-held requests).
8 |
9 | #### Http Polling
10 | Basically AJAX, using XmlHttpRequest.
11 |
12 | #### Http Long Polling
13 | Is still AJAX but the server holds on to the response unless the server has an update, as soon as the server has an update, it sends it and then the client can send another request. Disadvantage is the additional header data that needs to be sent back and forth causing additional overhead.
14 |
15 | #### Http Streaming
16 | Similar to long polling but the server responds with a header with `Transfer Encoding: chunked` and hence we do not need to initiate a new request every time the server sends some data (and hence save the additional header overhead). The drawback here is that we have to "understand" and figure out the structure of the data to distinguish between multiple chunks sent by the server.
17 |
18 | #### Java Applet, Flash, Silverlight
19 | They provide the ability to connect to socket servers over tcp/ip but since they are plugins, developers don't want to depend on them.
20 |
21 | --
22 | There are also some techniques with iframes that are not worth mentioning.
23 |
24 | ### Not Comet
25 | Basically, Comet is a term for a set of hacks to eneble server push. There are some new APIs that are not hacks:
26 |
27 | #### WebSockets
28 |
29 | WebSockets are the new API which tries to address the short comings of above methods in the following manner:
30 |
31 | * The advantage of WebSockets over plugins like Java Applets, Flash or Silverlight is that WebSockets are natively built into browsers and does not rely on plugins.
32 | * The advantage of WebSockets over http streaming is that you don't have to make an effort to "understand" and parse the data received.
33 | * The advantage of WebSockets over Long Polling is that of elimination of extra headers size & opening and closing of socket connection for request.
34 |
35 | #### Server-sent events
36 | Not fully supported yet
37 |
--------------------------------------------------------------------------------
/javascript/problems/stringsMix.md:
--------------------------------------------------------------------------------
1 | ## Task
2 |
3 | Given two strings s1 and s2, we want to visualize how different the two strings are. We will only take into account the lowercase letters (a to z). First let us count the frequency of each lowercase letters in s1 and s2.
4 | ```
5 | s1 = "A aaaa bb c"
6 |
7 | s2 = "& aaa bbb c d"
8 |
9 | s1 has 4 'a', 2 'b', 1 'c'
10 |
11 | s2 has 3 'a', 3 'b', 1 'c', 1 'd'
12 | ```
13 | So the maximum for 'a' in s1 and s2 is 4 from s1; the maximum for 'b' is 3 from s2. In the following we will not consider letters when the maximum of their occurrences is less than or equal to 1.
14 |
15 | We can resume the differences between s1 and s2 in the following string: "1:aaaa/2:bbb" where 1 in 1:aaaa stands for string s1 and aaaa because the maximum for a is 4. In the same manner 2:bbb stands for string s2 and bbb because the maximum for b is 3.
16 |
17 | The task is to produce a string in which each lowercase letters of s1 or s2 appears as many times as its maximum if this maximum is strictly greater than 1; these letters will be prefixed by the number of the string where they appear with their maximum value and :. If the maximum is in s1 as well as in s2 the prefix is =:.
18 |
19 | In the result, substrings will be in decreasing order of their length and when they have the same length sorted alphabetically (more precisely sorted by codepoint); the different groups will be separated by '/'.
20 |
21 | ## Solution
22 |
23 | ```js
24 | const compare = (x, y) => x === y ? 0 : x > y ? -1 : 1
25 |
26 | const comparator = (a, b) => {
27 | if (a.length !== b.length) {
28 | return compare(a.length, b.length)
29 | }
30 |
31 | return compare(b, a)
32 | }
33 |
34 | const mapLetters = string => (
35 | string.split('').reduce((prev, next) => {
36 | if (/[a-z]/.test(next)) {
37 | prev[next] = prev[next] + 1 || 1
38 | }
39 |
40 | return prev
41 | }, {})
42 | )
43 |
44 | function mix(s1, s2) {
45 | const used = {}
46 | const map1 = mapLetters(s1)
47 | const map2 = mapLetters(s2)
48 | const keys = Object.keys(map1).concat(Object.keys(map2))
49 | return keys.map(key => {
50 | if (!used[key]) {
51 | used[key] = true
52 | const n1 = map1[key] || 0
53 | const n2 = map2[key] || 0
54 | const number = Math.max(n1, n2)
55 |
56 | if (number > 1) {
57 | const start = n1 === n2 ? '=' : n1 > n2 ? 1 : 2
58 | return `${start}:${new Array(number).fill(key).join('')}`
59 | }
60 | }
61 | }).filter(a => a).sort(comparator).join('/')
62 | }
63 | ```
64 |
--------------------------------------------------------------------------------
/javascript/problems/levinshteinDistance.md:
--------------------------------------------------------------------------------
1 | You'll get an entered term (lowercase string) and an array of known words (also lowercase strings). Your task is to find out, which word from the dictionary is most similar to the entered one. The similarity is described by the minimum number of letters you have to add, remove or replace in order to get from the entered word to one of the dictionary. The lower the number of required changes, the higher the similarity between each two words.
2 |
3 | Same words are obviously the most similar ones. A word that needs one letter to be changed is more similar to another word that needs 2 (or more) letters to be changed. E.g. the mistyped term berr is more similar to beer (1 letter to be replaced) than to barrel (3 letters to be changed in total).
4 |
5 | Extend the dictionary in a way, that it is able to return you the most similar word from the list of known words.
6 |
7 | Code Examples:
8 |
9 | ```js
10 | fruits = new Dictionary(['cherry', 'pineapple', 'melon', 'strawberry', 'raspberry']);
11 | fruits.findMostSimilar('strawbery'); // must return "strawberry"
12 | fruits.findMostSimilar('berry'); // must return "cherry"
13 |
14 | things = new Dictionary(['stars', 'mars', 'wars', 'codec', 'codewars']);
15 | things.findMostSimilar('coddwars'); // must return "codewars"
16 |
17 | languages = new Dictionary(['javascript', 'java', 'ruby', 'php', 'python', 'coffeescript']);
18 | languages.findMostSimilar('heaven'); // must return "java"
19 | languages.findMostSimilar('javascript'); // must return "javascript" (same words are obviously the most similar ones)
20 | ```
21 |
22 | ### Solution
23 |
24 | ```js
25 | function Dictionary(words) {
26 | this.words = words;
27 | }
28 |
29 | function d(s1, s2) {
30 | const memo = {}
31 | return function _d(m, n, a1, a2) {
32 | let hash = `${m} ${n} ${s1[m - 1]} ${s2[n - 1]}`
33 | if (memo[hash]) return memo[hash]
34 | let res
35 | if (m == 0) {
36 | res = n
37 | } else if (n == 0) {
38 | res = m
39 | } else {
40 | res = Math.min(
41 | _d(m, n - 1) + 1,
42 | _d(m - 1, n) + 1,
43 | _d(m - 1, n - 1) + (s1[m - 1] === s2[n - 1] ? 0 : 1)
44 | )
45 | }
46 | memo[hash] = res
47 | return res
48 | }(s1.length, s2.length)
49 | }
50 |
51 | Dictionary.prototype.findMostSimilar = function(term) {
52 | return this.words.map(
53 | (word) => ({
54 | word,
55 | d: d(word, term)
56 | })
57 | ).reduce(
58 | (min, data) => data.d < min.d ? data : min
59 | ,{ word: '', d: Infinity }
60 | ).word
61 | }
62 | ```
63 |
--------------------------------------------------------------------------------
/css/cssBoxModel.md:
--------------------------------------------------------------------------------
1 | ## Explain what is CSS: the box model
2 |
3 | In a document, each element is represented as a rectangular box. Determining the size, properties — like its color, background, borders aspect — and the position of these boxes is the goal of the rendering engine.
4 |
5 | In CSS, each of these rectangular boxes is described using the standard box model. This model describes the content of the space taken by an element. Each box has four edges: the margin edge, border edge, padding edge, and content edge.
6 |
7 | oThe content area is the area containing the real content of the element. It often has a background, a color or an image (in that order, an opaque image hiding the background color) and is located inside the content edge; its dimensions are the content width, or content-box width, and the content height, or content-box height.
8 |
9 | If the CSS box-sizing property is set to default, the CSS properties width, min-width, max-width, height, min-height and max-height control the content size.
10 |
11 | The padding area extends to the border surrounding the padding. When the content area has a background, color, or image set on it, this will extend into the padding, which is why you can think of the padding as extending the content. The padding is located inside the padding edge, and its dimensions are the padding-box width and the padding-box height.
12 |
13 | The space between the padding and the content edge can be controlled using the padding-top, padding-right, padding-bottom, padding-left and the shorthand padding CSS properties.
14 |
15 | The border area extends the padding area to the area containing the borders. It is the area inside the border edge, and its dimensions are the border-box width and the border-box height. This area depends on the size of the border that is defined by the border-width property or the shorthand border.
16 |
17 | The margin area extends the border area with an empty area used to separate the element from its neighbors. It is the area inside the margin edge, and its dimensions are the margin-box width and the margin-box height.
18 |
19 | The size of the margin area is controlled using the margin-top, margin-right, margin-bottom, margin-left and the shorthand margin CSS properties.
20 |
21 | When margin collapsing happens, the margin area is not clearly defined since margins are shared between boxes.
22 |
23 | Finally, note that, for non-replaced inline elements, the amount of space taken up (the contribution to the height of the line) is determined by the line-height property, even though the border and padding appear visually around the content.
24 |
--------------------------------------------------------------------------------
/javascript/bind.md:
--------------------------------------------------------------------------------
1 | ## Explain `Function.prototype.bind`
2 |
3 | The `bind()` method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when this function is called.
4 |
5 | ```js
6 | const bindedFunction = fn.bind(thisArg[, arg1[, arg2[, ...]]])
7 | ```
8 | `thisArg` is ignored if `bindedFunction` is constructed using `new` operator.
9 |
10 | ### Spec description
11 |
12 | New **Bound function (BF)** is an **exotic function object** that wraps the original function object. **BF** has the following internal properties:
13 |
14 | - **[[BoundTargetFunction]]** - the wrapped function object;
15 | - **[[BoundThis]]** - the value that is always passed as the this value when calling the wrapped function.
16 | - **[[BoundArguments]]** - a list of values whose elements are used as the first arguments to any call to the wrapped function.
17 | - **[[Call]]** - executes code associated with this object. Invoked via a function call expression. The arguments to the internal method are a this value and a list containing the arguments passed to the function by a call expression.
18 |
19 | A bound function may also be constructed using the new operator: doing so acts as though the target function had instead been constructed. The provided this value is ignored, while prepended arguments are provided to the emulated function.
20 |
21 | ### Use cases
22 |
23 | - Creating a bound function
24 |
25 | ```js
26 | this.x = 9;
27 | var module = {
28 | x: 81,
29 | getX: function() { return this.x; }
30 | };
31 |
32 | module.getX(); // 81
33 |
34 | var retrieveX = module.getX;
35 | retrieveX();
36 | // returns 9 - The function gets invoked at the global scope
37 |
38 | // Create a new function with 'this' bound to module
39 | // New programmers might confuse the
40 | // global var x with module's property x
41 | var boundGetX = retrieveX.bind(module);
42 | boundGetX(); // 81
43 | ```
44 |
45 | - Partially applied functions
46 |
47 | ```js
48 | function list() {
49 | return Array.prototype.slice.call(arguments);
50 | }
51 |
52 | var list1 = list(1, 2, 3); // [1, 2, 3]
53 |
54 | // Create a function with a preset leading argument
55 | var leadingThirtysevenList = list.bind(null, 37);
56 |
57 | var list2 = leadingThirtysevenList();
58 | // [37]
59 |
60 | var list3 = leadingThirtysevenList(1, 2, 3);
61 | // [37, 1, 2, 3]
62 | ```
63 |
64 | - With `setTimeout` to access specific context instead of default global object
65 | - Bound functions used as constructors (partial constructor application)
66 | - Creating shortcuts
67 |
--------------------------------------------------------------------------------
/network/CSRF.md:
--------------------------------------------------------------------------------
1 | ## Cross-Site Request Forgery
2 |
3 | Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request. With a little help of social engineering (such as sending a link via email or chat), an attacker may trick the users of a web application into executing actions of the attacker's choosing. If the victim is a normal user, a successful CSRF attack can force the user to perform state changing requests like transferring funds, changing their email address, and so forth. If the victim is an administrative account, CSRF can compromise the entire web application.
4 |
5 | ### Prevention measures that do NOT work
6 |
7 | - **Using a secret cookie**
8 |
9 | Remember that all cookies, even the secret ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request. Furthermore, session identifiers are simply used by the application container to associate the request with a specific session object. The session identifier does not verify that the end-user intended to submit the request.
10 |
11 | - **Only accepting POST requests**
12 |
13 | Applications can be developed to only accept POST requests for the execution of business logic. The misconception is that since the attacker cannot construct a malicious link, a CSRF attack cannot be executed. Unfortunately, this logic is incorrect. There are numerous methods in which an attacker can trick a victim into submitting a forged POST request, such as a simple form hosted in an attacker's Website with hidden values. This form can be triggered automatically by JavaScript or can be triggered by the victim who thinks the form will do something else.
14 |
15 | A number of flawed ideas for defending against CSRF attacks have been developed over time. Here are a few that we recommend you avoid.
16 |
17 | - **Multi-Step Transactions**
18 |
19 | Multi-Step transactions are not an adequate prevention of CSRF. As long as an attacker can predict or deduce each step of the completed transaction, then CSRF is possible.
20 |
21 | - **URL Rewriting**
22 |
23 | This might be seen as a useful CSRF prevention technique as the attacker cannot guess the victim's session ID. However, the user’s session ID is exposed in the URL. We don't recommend fixing one security flaw by introducing another.
24 |
25 | - **HTTPS**
26 |
27 | HTTPS does nothing to defend against CSRF.
28 |
29 |
--------------------------------------------------------------------------------
/javascript/problems/snailSort.md:
--------------------------------------------------------------------------------
1 | # Snail Sort
2 |
3 | ## Problem
4 | Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
5 |
6 | ```
7 | array = [[1,2,3],
8 | [4,5,6],
9 | [7,8,9]]
10 | snail(array) #=> [1,2,3,6,9,8,7,4,5]
11 | ```
12 | For better understanding, please follow the numbers of the next array consecutively:
13 |
14 | ```
15 | array = [[1,2,3],
16 | [8,9,4],
17 | [7,6,5]]
18 | snail(array) #=> [1,2,3,4,5,6,7,8,9]
19 | ```
20 |
21 | NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.
22 |
23 | NOTE 2: The 0×0 (empty matrix) is represented as `[[]]`
24 |
25 | ## Solution
26 | ```js
27 | snail = function(a) {
28 | const n = a[0].length
29 | const res = []
30 | let i = 0
31 | let j = 0
32 |
33 | while (res.length < (n * n)) {
34 | res.push(a[i][j])
35 | if (j + 2 > i && j < n - 1 - i) {
36 | j++
37 | continue
38 | }
39 | if (j + 1 >= n / 2 && i < j) {
40 | i++
41 | continue
42 | }
43 | if (i + 1 >= n / 2 && j > n - 1 - i) {
44 | j--
45 | continue
46 | }
47 | if (j + 1 <= n / 2 && i > j + 1) {
48 | i--
49 | continue
50 | }
51 | }
52 | return res
53 | }
54 | ```
55 |
56 | ## Nicer solution
57 | ```js
58 | snail = function(array) {
59 | var result;
60 | while (array.length) {
61 | // Steal the first row.
62 | result = (result ? result.concat(array.shift()) : array.shift());
63 | // Steal the right items.
64 | for (var i = 0; i < array.length; i++)
65 | result.push(array[i].pop());
66 | // Steal the bottom row.
67 | result = result.concat((array.pop() || []).reverse());
68 | // Steal the left items.
69 | for (var i = array.length - 1; i >= 0; i--)
70 | result.push(array[i].shift());
71 | }
72 | return result;
73 | }
74 | ```
75 |
76 | ## Recursive (not super nice)
77 | ```js
78 | function snail(array, level = 0, res = []) {
79 | const length = array[0].length
80 | const rightIndex = length - 1 - level
81 |
82 | if (res.length === length ** 2) {
83 | return res
84 | }
85 |
86 | if (level === rightIndex) {
87 | res.push(array[level][level])
88 | return res
89 | }
90 |
91 | for (let i = 0; i < 4; i++) {
92 | for (let j = level; j < rightIndex; j++) {
93 | if (i === 0) res.push(array[level][j])
94 | if (i === 1) res.push(array[j][rightIndex])
95 | if (i === 2) res.push(array[rightIndex][length - 1 - j])
96 | if (i === 3) res.push(array[length - 1 - j][level])
97 | }
98 | }
99 |
100 | return snail(array, level + 1, res)
101 | }
102 | ```
103 |
--------------------------------------------------------------------------------
/databases/capTheorem.md:
--------------------------------------------------------------------------------
1 | # What is CAP Theorem?
2 |
3 | CAP theorem is designed for distributed file systems(collection of interconnected nodes).
4 | CAP Theorem also known as Brewer’s theorem and used to distributed consistency.
5 | it contains follwing three technical terms for distributed systems.
6 |
7 | C – *Consistency*
8 |
9 | A – *Availability*
10 |
11 | P – *Partition Tolerance*
12 |
13 | ### Consistency:
14 |
15 | When you read data it will give same data how many times read and server send response each and every request but systems always consistent when read data.(all node having same data)
16 |
17 | ### Availability:
18 |
19 | It means all requests give response and no error accured in this systems.
20 |
21 | ### Partition Tolerance:
22 |
23 | All functions run all time when more nodes not responsive and commnication break between two nodes
24 |
25 | It's theoretically impossible to have all 3 requirements met, so a combination of 2 must be chosen and this is usually the deciding factor in what technology is used.
26 |
27 | When it comes to distributed databases, the two choices are only AP or CP because if it's not partition tolerant,
28 | it's not really a reliable distributed database.
29 | So the choice is simpler:
30 | * if a network split happens, do you want the database to keep answering but with possibly old/bad data (AP)?
31 | * Or should it just stop responding unless you can get the absolute latest copy (CP)?
32 |
33 | # ACID
34 |
35 | This describes a set of properties that apply to data transactions, defined as follows:
36 |
37 | **Atomicity** - Everything in a transaction must happen successfully or none of the changes are committed. This avoids a transaction that changes multiple pieces of data from failing halfway and only making a few changes.
38 |
39 | **Consistency** - The data will only be committed if it passes all the rules in place in the database (ie: data types, triggers, constraints, etc).
40 |
41 | **Isolation** - Transactions won't affect other transactions by changing data that another operation is counting on; and other users won't see partial results of a transaction in progress (depending on isolation mode).
42 |
43 | **Durability** - Once data is committed, it is durably stored and safe against errors, crashes or any other (software) malfunctions within the database.
44 |
45 | # Tying it all together
46 |
47 | **CAP** provides the *basic requirements that a distributed system must follow* and **ACID** is a *set of rules that a database can choose to follow that guarantees how it handles transactions and keeps data safe*.
48 |
49 | * There are lots of options other than relational databases for storing more or different kinds of data and they often use a distributed set of servers working together and are designed either for AP or CP under the CAP theorem.
50 | * When it comes to how safe the committed data is, any ACID compliant system can be considered reliable.
51 |
--------------------------------------------------------------------------------
/html/standartModes.md:
--------------------------------------------------------------------------------
1 | ## What's the difference between full standards mode, almost standards mode and quirks mode?
2 |
3 | In the old days of the web, pages were typically written in two versions: One for Netscape Navigator, and one for Microsoft Internet Explorer. When the web standards were made at W3C, browsers could not just start using them, as doing so would break most existing sites on the web. Browsers therefore introduced two modes to treat new standards compliant sites differently from old legacy sites.
4 |
5 | There are now three modes used by the layout engines in web browsers: quirks mode, almost standards mode, and full standards mode. In quirks mode, layout emulates nonstandard behavior in Navigator 4 and Internet Explorer 5. This is essential in order to support websites that were built before the widespread adoption of web standards.
6 |
7 | ### Full standards mode
8 |
9 | In standards-compliant mode, the web browser assumes the page has been authored to the web content specification declared; code that does not conform to the declared standard may not display, or may display incorrectly.
10 | For a web browser’s standards-compliant mode to be triggered, the webpage must have a complete document type declaration, including the URI to the document type definition (DTD).
11 |
12 | ### Almost strict mode
13 |
14 | "Almost standards" rendering mode is exactly the same as "standards" mode in all details save one, where it works like "quirks" mode: the height calculations for line boxes and some of the inline elements in them.
15 |
16 | In the early days, experiments with strict mode invariably raised the comment that images suddenly got an odd bottom margin that couldn’t be removed. The cause was that in strict mode is an inline element, which means that some space should be reserved for possible descender characters like g, j, or q. Of course an image doesn’t have descender characters, so the space was never used, but it still had to be reserved.
17 |
18 | The solution was to explicitly declare images block level elements: img {display: block}.
19 |
20 | Nonetheless browser vendors, Mozilla especially, thought this was such a confusing situation that they introduced "almost strict mode". This was defined as strict mode, but with images continuing to be blocks, and not inline elements.
21 |
22 | ### Quirks mode
23 |
24 | In quirks mode, the web browser attempts to render code based on a ‘best-guess’, this includes a generous interpretation of code that may be non-standard or poorly-formed.
25 |
26 | For HTML documents, browsers use a DOCTYPE in the beginning of the document to decide whether to handle it in quirks mode or standards mode. To ensure that your page uses full standards mode, make sure that your page has a DOCTYPE like in this example:
27 |
28 | ```html
29 |
30 |
31 |
32 |
33 | Hello World!
34 |
35 |
36 |
37 |
38 | ```
39 |
--------------------------------------------------------------------------------
/html/dataAttributes.md:
--------------------------------------------------------------------------------
1 | ## What are `data-` attributes good for?
2 |
3 | HTML5 is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. `data-*` attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, extra properties on DOM, or `setUserData`.
4 |
5 | ### HTML Syntax
6 | The syntax is simple. Any attribute on any element whose attribute name starts with `data-` is a data attribute. Say you have an article and you want to store some extra information that doesn’t have any visual representation. Just use data attributes for that:
7 |
8 | ```html
9 |
14 | ...
15 |
16 | ```
17 |
18 | ### JavaScript Access
19 | Reading the values of these attributes out in JavaScript is also very simple. You could use `getAttribute()` with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.
20 |
21 | To get a data attribute through the dataset object, get the property by the part of the attribute name after `data-` (note that dashes are converted to camelCase).
22 |
23 | ```js
24 | var article = document.getElementById('electriccars');
25 |
26 | article.dataset.columns // "3"
27 | article.dataset.indexNumber // "12314"
28 | article.dataset.parent // "cars"
29 | ```
30 |
31 | Each property is a string and can be read and written. In the above case setting `article.dataset.columns = 5` would change that attribute to "5".
32 |
33 |
34 | ### CSS Access
35 | Note that, as data attributes are plain HTML attributes, you can even access them from CSS. For example to show the parent data on the article you can use generated content in CSS with the `attr()` function:
36 |
37 | ```css
38 | article::before {
39 | content: attr(data-parent);
40 | }
41 | You can also use the attribute selectors in CSS to change styles according to the data:
42 |
43 | article[data-columns='3'] {
44 | width: 400px;
45 | }
46 | article[data-columns='4'] {
47 | width: 600px;
48 | }
49 | ```
50 |
51 | ### Issues
52 | Do not store content that should be visible and accessible in data attributes, because assistive technology may not access them. In addition, search crawlers may not index data attributes' values.
53 |
54 | The main issues to consider are Internet Explorer support and performance. Internet Explorer 11+ provides support for the standard, but all earlier versions do not support `dataset`. To support IE 10 and under you need to access data attributes with `getAttribute() ` instead. Also, the performance of reading data-attributes compared to storing this data in a JS data warehouse is poor. Using `dataset` is even slower than reading the data out with `getAttribute()`.
55 |
56 | That said, though, for custom element-associated metadata, they are a great solution.
57 |
--------------------------------------------------------------------------------
/network/httpVsHttps.md:
--------------------------------------------------------------------------------
1 | ## HTTP vs HTTPS
2 |
3 | ### What is HTTPS
4 |
5 | Hyper Text Transfer Protocol Secure (HTTPS) is the secure version of HTTP, the protocol over which data is sent between your browser and the website that you are connected to. The 'S' at the end of HTTPS stands for 'Secure'. It means all communications between your browser and the website are encrypted. HTTPS is often used to protect highly confidential online transactions like online banking and online shopping order forms.
6 |
7 | ### How it works
8 |
9 | HTTPS pages typically use one of two secure protocols to encrypt communications - SSL (Secure Sockets Layer) or TLS (Transport Layer Security). Both the TLS and SSL protocols use what is known as an 'asymmetric' Public Key Infrastructure (PKI) system. An asymmetric system uses two 'keys' to encrypt communications, a 'public' key and a 'private' key. Anything encrypted with the public key can only be decrypted by the private key and vice-versa.
10 |
11 | As the names suggest, the 'private' key should be kept strictly protected and should only be accessible the owner of the private key. In the case of a website, the private key remains securely ensconced on the web server. Conversely, the public key is intended to be distributed to anybody and everybody that needs to be able to decrypt information that was encrypted with the private key.
12 |
13 | ### What is HTTPS certificate
14 |
15 | When you request a HTTPS connection to a webpage, the website will initially send its SSL certificate to your browser. This certificate contains the public key needed to begin the secure session. Based on this initial exchange, your browser and the website then initiate the 'SSL handshake'. The SSL handshake involves the generation of shared secrets to establish a uniquely secure connection between yourself and the website.
16 |
17 | When a trusted SSL Digital Certificate is used during a HTTPS connection, users will see a padlock icon in the browser address bar. When an Extended Validation Certificate is installed on a web site, the address bar will turn green.
18 |
19 | ### Why Is an SSL Certificate Required?
20 |
21 | All communications sent over regular HTTP connections are in 'plain text' and can be read by any hacker that manages to break into the connection between your browser and the website. This presents a clear danger if the 'communication' is on an order form and includes your credit card details or social security number. With a HTTPS connection, all communications are securely encrypted. This means that even if somebody managed to break into the connection, they would not be able decrypt any of the data which passes between you and the website.
22 |
23 | ### Benefits
24 |
25 | The major benefits of a HTTPS certificate are:
26 |
27 | - Customer information, like credit card numbers, is encrypted and cannot be intercepted
28 | - Visitors can verify you are a registered business and that you own the domain
29 | - Customers are more likely to trust and complete purchases from sites that use HTTPS
30 |
--------------------------------------------------------------------------------
/javascript/eventFlow.md:
--------------------------------------------------------------------------------
1 | ## What is event bubbling and capturing?
2 |
3 | 
4 |
5 | Event objects are dispatched to an event target. But before dispatch can begin, the event object’s propagation path must first be determined.
6 |
7 | The propagation path is an ordered list of current event targets through which the event passes. This propagation path reflects the hierarchical tree structure of the document. The last item in the list is the event target, and the preceding items in the list are referred to as the target’s ancestors, with the immediately preceding item as the target’s parent.
8 |
9 | Once the propagation path has been determined, the event object passes through one or more event phases. There are three event phases: capture phase, target phase and bubble phase. Event objects complete these phases as described below. A phase will be skipped if it is not supported, or if the event object’s propagation has been stopped. For example, if the `bubbles` attribute is set to false, the bubble phase will be skipped, and if `stopPropagation()` has been called prior to the dispatch, all phases will be skipped.
10 |
11 | - **The capture phase**: The event object propagates through the target’s ancestors from the Window to the target’s parent. This phase is also known as the capturing phase.
12 |
13 | - **The target phase**: The event object arrives at the event object’s event target. This phase is also known as the at-target phase. If the event type indicates that the event doesn’t bubble, then the event object will halt after completion of this phase.
14 |
15 | - **The bubble phase**: The event object propagates through the target’s ancestors in reverse order, starting with the target’s parent and ending with the Window. This phase is also known as the bubbling phase.
16 |
17 | ```js
18 | element1.addEventListener('click', doSomething2, true) // captruring phase
19 | element2.addEventListener('click', doSomething, false) // bubbling phase
20 | ```
21 |
22 | If the user clicks on element2 the following happens:
23 |
24 | 1. The click event starts in the capturing phase. The event looks if any ancestor element of element2 has a onclick event handler for the capturing phase.
25 |
26 | 2. The event finds one on element1. `doSomething2()` is executed.
27 |
28 | 3. The event travels down to the target itself, no more event handlers for the capturing phase are found. The event moves to its bubbling phase and executes `doSomething()`, which is registered to element2 for the bubbling phase.
29 |
30 | 4. The event travels upwards again and checks if any ancestor element of the target has an event handler for the bubbling phase. This is not the case, so nothing happens.
31 |
32 | ### Stop Immediate Propagation
33 |
34 | If several listeners are attached to the same element for the same event type, they are called in order in which they have been added. If during one such call, `event.stopImmediatePropagation()` is called, no remaining listeners will be called.
35 |
--------------------------------------------------------------------------------
/javascript/primitives.md:
--------------------------------------------------------------------------------
1 | ## What is primitive data type?
2 |
3 | A **primitive** (primitive value, primitive data type) is data that is not an object and has no methods. In JavaScript, there are 6 primitive data types: `string`, `number`, `boolean`, `null`, `undefined`, `symbol` (new in *ECMAScript 2015*).
4 |
5 | Most of the time, a primitive value is represented directly at the lowest level of the language implementation.
6 |
7 | All primitives are **immutable** (cannot be changed).
8 |
9 | A primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit. The number type is the largest of the primitive types. If each JavaScript variable reserves eight bytes of memory, the variable can directly hold any primitive value.
10 |
11 | Strings may have different length so that cannot be stored directly in a variable. And they looks like just an *array* of *characters* because they have methods like `length()`, `concat()` and `indexOf()`. But it's a primitive in Javascript. Implementation of strings lays somewhere in between primitives and objects. The difference with objects is that strings are **immutalbe** like all other primitive data types.
12 |
13 | Reference types are another matter, however. Objects, for example, can be of any length -- they do not have a fixed size. Since these types do not have a fixed size, their values cannot be stored directly in the eight bytes of memory associated with each variable. Instead, the variable stores a reference to the value. Typically, this reference is some form of pointer or memory address. It is not the data value itself, but it tells the variable where to look to find the value.
14 |
15 | The distinction between primitive and reference types is an important one, as they behave differently. Consider the following code that uses numbers (a primitive type):
16 |
17 | ```js
18 | let a = 3.14 // Declare and initialize a variable
19 | let b = a // Copy the variable's value to a new variable
20 | a = 4 // Modify the value of the original variable
21 | alert(b) // Displays 3.14; the copy has not changed
22 | ```
23 |
24 | There is nothing surprising about this code. Now consider what happens if we change the code slightly so that it uses arrays (a reference type) instead of numbers:
25 |
26 | ```js
27 | let a = [1, 2, 3] // Initialize a variable to refer to an array
28 | let b = a // Copy that reference into a new variable
29 | a[0] = 99 // Modify the array using the original reference
30 | alert(b) // Display the changed array [99, 2, 3] using the new reference
31 | ```
32 |
33 | ### Primitive wrapper objects in JavaScript
34 | Except for `null` and `undefined`, all primitive values have object equivalents that wrap around the primitive values:
35 |
36 | - `String` for the string primitive.
37 | - `Number` for the number primitive.
38 | - `Boolean` for the Boolean primitive.
39 | - `Symbol` for the Symbol primitive.
40 |
41 | The wrapper's `valueOf()` method returns the primitive value.
42 |
--------------------------------------------------------------------------------
/javascript/problems/binaryTreeTraversal.md:
--------------------------------------------------------------------------------
1 | ## Given the root node of a binary tree (but not necessarily a binary search tree,) write three functions that will print the tree in pre-order, in-order, and post-order.
2 |
3 | A Node has the following properties:
4 |
5 | ```js
6 | var data; // A number or string.
7 | Node left; // Undefined if there is no left child.
8 | Node right; // Undefined if there is no right child.
9 | ```
10 |
11 | The structure of a tree looks like:
12 |
13 | ```js
14 | data Tree a = Nil | Node (Tree a) a (Tree a)
15 | ```
16 |
17 | Pre-order means that we
18 |
19 | 1. Visit the root.
20 | 2. Traverse the left subtree (left node.)
21 | 3. Traverse the right subtree (right node.)
22 |
23 | In-order means that we
24 |
25 | 1. Traverse the left subtree (left node.)
26 | 2. Visit the root.
27 | 3. Traverse the right subtree (right node.)
28 |
29 | Post-order means that we
30 |
31 | 1. Traverse the left subtree (left node.)
32 | 2. Traverse the right subtree (right node.)
33 | 3. Visit the root.
34 |
35 | Let's say we have three Nodes.
36 |
37 | ```js
38 | var a = new Node("A");
39 | var b = new Node("B");
40 | var c = new Node("C");
41 |
42 | a.left = b;
43 | a.right = c;
44 | ```
45 |
46 | Then, preOrder(a) should return `["A", "B", C"]`
47 | inOrder(a) should return `["B", "A", "C"]`
48 | postOrder(a) should return `["B", "C", A"]`
49 |
50 | What would happen if we did this?
51 |
52 | ```js
53 | var d = new Node("D");
54 | c.left = d;
55 | ```
56 |
57 | preOrder(a) should return `["A", "B", "C", "D"]`
58 | inOrder(a) should return `["B", "A", "D", "C"]`
59 | postOrder(a) should return `["B", "D", "C", "A"]`
60 |
61 | ## Solution
62 | ```js
63 | const toArray = (node, f) => node ? f(node) : []
64 |
65 | // 1.) Root node, 2.) traverse left subtree, 3.) traverse right subtree.
66 | function preOrder(node)
67 | {
68 | return [
69 | node.data,
70 | ...toArray(node.left, preOrder),
71 | ...toArray(node.right, preOrder),
72 | ]
73 | }
74 |
75 | // 1.) Traverse left subtree, 2.) root node, 3.) traverse right subtree.
76 | function inOrder(node)
77 | {
78 | return [
79 | ...toArray(node.left, inOrder),
80 | node.data,
81 | ...toArray(node.right, inOrder),
82 | ]
83 | }
84 |
85 | // 1.) Traverse left subtree, 2.) traverse right subtree, 3.) root node.
86 | function postOrder(node)
87 | {
88 | return [
89 | ...toArray(node.left, postOrder),
90 | ...toArray(node.right, postOrder),
91 | node.data,
92 | ]
93 | }
94 | ```
95 |
96 | ## ES5 solution
97 |
98 | ```js
99 | function preOrder(node) {
100 | return node == null || node.data == null ? [] : [node.data].concat(preOrder(node.left)).concat(preOrder(node.right));
101 | }
102 | function inOrder(node) {
103 | return node == null || node.data == null ? [] : inOrder(node.left).concat(node.data).concat(inOrder(node.right));
104 | }
105 | function postOrder(node) {
106 | return node == null || node.data == null ? [] : postOrder(node.left).concat(postOrder(node.right)).concat(node.data);
107 | }
108 | ```
109 |
--------------------------------------------------------------------------------
/javascript/prototypes.md:
--------------------------------------------------------------------------------
1 | ## How prototypal inheritance works
2 |
3 | JavaScript objects are dynamic "bags" of properties (referred to as own properties). Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with `null` as its prototype. `null`, by definition, has no prototype, and acts as the final link in this prototype chain. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.
4 |
5 | Traditional `new` inheritance:
6 |
7 | The new operator takes a function F and arguments: new F(arguments...). It does three easy steps:
8 | - Create the instance of the class. It is an empty object with its __proto__ property set to F.prototype.
9 | - Initialize the instance. The function F is called with the arguments passed and this set to be the instance.
10 | - Return the instance
11 |
12 | ```js
13 | function New (f) {
14 | var n = { '__proto__': f.prototype }
15 |
16 | return function () {
17 | f.apply(n, arguments)
18 | return n
19 | }
20 | }
21 |
22 | function Point(x, y) {
23 | this.x = x
24 | this.y = y
25 | }
26 |
27 | Point.prototype = {
28 | print: function () {
29 | console.log(this.x, this.y)
30 | }
31 | }
32 |
33 | var p = new Point(10, 20)
34 | p.print() // 10 20
35 | ```
36 |
37 | ECMAScript 5 introduced a new method: Object.create(). Calling this method creates a new object. The prototype of this object is the first argument of the function:
38 |
39 | ```js
40 | Object.create = function (parent) {
41 | function F() {}
42 | F.prototype = parent
43 | return new F()
44 | }
45 |
46 | // Same polyfill using deprecated `__proto__` property
47 | Object.create = function (parent) {
48 | return { '__proto__': parent }
49 | }
50 |
51 | var Point = {
52 | x: 0,
53 | y: 0,
54 | print: function () {
55 | console.log(this.x, this.y)
56 | }
57 | }
58 |
59 | var p = Object.create(Point)
60 | p.x = 10
61 | p.y = 20
62 | p.print() // 10 20
63 | ```
64 | The lookup time for properties that are high up on the prototype chain can have a negative impact on performance, and this may be significant in code where performance is critical. Additionally, trying to access nonexistent properties will always traverse the full prototype chain.
65 |
66 |
67 | Another example:
68 | ```js
69 | function Parent(name) {
70 | this.name = name
71 | }
72 |
73 | Parent.prototype = {
74 | sayLol() {
75 | console.log(this.name + ' lol')
76 | }
77 | }
78 |
79 | p = new Parent('bob')
80 | p.sayLol()
81 | console.log('------ after Parent ------')
82 |
83 | function Child(lastname) {
84 | Parent.call(this, lastname)
85 | this.lastname = lastname
86 | }
87 |
88 | Child.prototype = Object.create(Parent.prototype)
89 | Child.prototype.constructor = Child
90 |
91 | Child.prototype.sayOmg = function() {
92 | console.log(this.lastname + ' omg')
93 | }
94 |
95 | c = new Child('dilan')
96 | c.sayLol()
97 | c.sayOmg()
98 | ```
99 |
--------------------------------------------------------------------------------
/clojure/macros.md:
--------------------------------------------------------------------------------
1 | ## Explain macros
2 |
3 | Clojure has a programmatic macro system which allows the compiler to be extended by user code. Macros can be used to define syntactic constructs which would require primitives or built-in support in other languages. Many core constructs of Clojure are not, in fact, primitives, but are normal macros.
4 |
5 | Some macros produce simple combinations of primitive forms. For example, when combines if and do:
6 |
7 | ```clj
8 | user=> (macroexpand '(when (pos? a) (println "positive") (/ b a)))
9 | (if (pos? a) (do (println "positive") (/ b a)))
10 | ```
11 |
12 | Other macros re-arrange forms in useful ways, like the -> macro, which recursively inserts each expression as the first argument of the next expression:
13 |
14 | ```clj
15 | user=> (-> {} (assoc :a 1) (assoc :b 2))
16 | {:b 2, :a 1}
17 | user=> (macroexpand '(-> {} (assoc :a 1) (assoc :b 2)))
18 | (assoc (clojure.core/-> {} (assoc :a 1)) :b 2)
19 | ```
20 |
21 | ### Special variables
22 |
23 | Two special variables are available inside defmacro for more advanced usages:
24 |
25 | * `&form` - the actual form (as data) that is being invoked
26 | * `&env` - a map of local bindings at the point of macro expansion. The env map is from symbols to objects holding compiler information about that binding.
27 |
28 | In general, Clojure macros are potentially useful for many reasons:
29 |
30 | * Control structures - it's possible to create certain control structures using macros that can never be represented as functions. For example, you can't write if as a function, because if it was a function then it would have to evaluate all three arguments, whereas with a macro you can make it only evaluate two (the condition value and either the true or false expression)
31 | * Compile time optimisation - sometimes you want to optimise your code based on a constant that is known or can be computed at compile time. For example, you could create a "logging" function that logs only if the code was compiled in debug mode, but creates zero overhead in the production application.
32 | * Code generation / boilerplate elimination - if you need to produce a lot of very similar code with similar structure, then you can use macros to automatically generate these from a few parameters. If you hate boilerplate, then macros are your friends.
33 | * Creating new syntax - if you see the need for a particular piece of syntax that would be useful (perhaps encapsulating a common pattern) then you can create a macro to implement this. Some DSLs for example can be simplified with additional syntax.
34 | * Creating a new language with entirely new semantics (Credits to SK-Logic!) theoretically you could even go so far to create a new language using macros, which would effectively compile your new language down into Clojure. The new langauge would not even have to be Lisp-like: it could parse and compile arbitrary strings for example.
35 |
36 | One important piece of advice is only use macros if you need them and functions won't work. Most problems can be solved with functions. Apart for the fact that macros are overkill for simple cases, functions have some intrinsic advantages: they are more flexible, can be stored in data structures, can be passed as parameters to higher order functions, are a bit easier for people to understand etc.
37 |
--------------------------------------------------------------------------------
/javascript/httpPolling.md:
--------------------------------------------------------------------------------
1 | ## What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?
2 |
3 | Before you can understand these technologies, you have to understand classic HTTP web traffic first.
4 |
5 | ### Regular HTTP:
6 |
7 | - A client requests a webpage from a server.
8 | - The server calculates the response
9 | - The server sends the response to the client.
10 |
11 | 
12 |
13 | ### Ajax Polling:
14 |
15 | - A client requests a webpage from a server using regular HTTP (see HTTP above).
16 | - The requested webpage executes JavaScript which requests a file from the server at regular intervals (e.g. 0.5 seconds).
17 | - The server calculates each response and sends it back, just like normal HTTP traffic.
18 |
19 | 
20 |
21 | ### Ajax Long-Polling:
22 |
23 | - A client requests a webpage from a server using regular HTTP (see HTTP above).
24 | - The requested webpage executes JavaScript which requests a file from the server.
25 | - The server does not immediately respond with the requested information but waits until there's new information available.
26 | - When there's new information available, the server responds with the new information.
27 | - The client receives the new information and immediately sends another request to the server, re-starting the process.
28 |
29 | 
30 |
31 | ### HTML5 Server Sent Events (SSE) / EventSource:
32 |
33 | - A client requests a webpage from a server using regular HTTP (see HTTP above).
34 | - The requested webpage executes javascript which opens a connection to the server.
35 | - The server sends an event to the client when there's new information available.
36 | - Real-time traffic from server to client, mostly that's what you'll need
37 | - You'll want to use a server that has an event loop
38 | - Not possible to connect with a server from another domain
39 |
40 | 
41 |
42 | ### HTML5 Websockets:
43 |
44 | - A client requests a webpage from a server using regular http (see HTTP above).
45 | - The requested webpage executes JavaScript which opens a connection with the server.
46 | - The server and the client can now send each other messages when new data (on either side) is available.
47 | - Real-time traffic from the server to the client and from the client to the server
48 | - You'll want to use a server that has an event loop
49 | - With WebSockets it is possible to connect with a server from another domain.
50 | - It is also possible to use a third party hosted websocket server, for example Pusher or others. This way you'll only have to implement the client side, which is very easy!
51 |
52 | 
53 |
54 | ### Comet:
55 |
56 | Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it. Comet is an umbrella term, encompassing multiple techniques for achieving this interaction. All these methods rely on features included by default in browsers, such as JavaScript, rather than on non-default plugins. The Comet approach differs from the original model of the web, in which a browser requests a complete web page at a time.
57 |
58 | (Streaming, Hidden iframe, XMLHttpRequest, Ajax with long polling, XMLHttpRequest long polling, Script tag long polling)
59 |
--------------------------------------------------------------------------------
/javascript/jsonp.md:
--------------------------------------------------------------------------------
1 | ## Explain how JSONP works (and how it's not really Ajax).
2 |
3 | Stands for JavaScript Object Notation with Padding
4 |
5 | Browsers try to be security conscious. They don’t let your JS talk to just any old server (see Cross Site Scripting). When you make AJAX requests, you can only query your server, not anyone else’s. This is a problem if you want to get data from another server (perhaps see a stream of Tweets). The browsers will not let you make an AJAX call to another server, so you're stuck.
6 |
7 | Well, browsers have a caveat. You aren’t allowed to call other servers from your JS, but you are allowed to include a script from another server. You probably already do this with jQuery. Most people include a script tag to get jQuery hosted from Google rather than hosting it themselves. Something like this:
8 |
9 | ``
10 | Notice that the domain is ajax.googleapis.com not your-awesome-site.com. Browsers allow this kind of code sharing, but direct calls to an API from JS.
11 |
12 | So way back in 2005 someone had the clever idea to take advantage of this caveat. Instead of calling an API directly (which browsers don’t allow) you can call it via a script tag (which is totally legit).
13 |
14 | So how does it work?
15 |
16 | Create a function in the global space to handle the JSON returned from the API. It doesn’t have to do much, just enough so you can see what you're getting:
17 |
18 | ```js
19 | function myCallbackFunction(data) {
20 | console.log(data);
21 | }
22 | ```
23 |
24 | Next, add a script tag to your page which calls the API and passes it an additional parameter. Something like this:
25 |
26 | ``
27 | Notice the additional parameter? It’s typically called callback, but not always, check the docs for your particular API. Also note the callback parameter’s value. It’s the same as the function we defined earlier. This is crucial! If those names don’t match up you won’t get your data.
28 |
29 | An API that’s set up to handle JSONP knows to look for that special parameter. If it’s there, the response isn’t just JSON, but the JSON wrapped (Padded) with the name of the callback. So for us, the API would return:
30 |
31 | ```js
32 | myCallbackFunction({'awesome': 'data'});
33 | ```
34 |
35 | Since the API returns to a script tag the JS is immediately executed. So myCallbackFunction gets called. We defined this function earlier, so we'll have `{'awesome': 'data'}` logged to the console!
36 |
37 | A few things to note:
38 |
39 | Generally you don’t write the script tag yourself. You can get jQuery to do that for you :) To make the same call as we did previously you can just use:
40 |
41 | ```js
42 | $.ajax({
43 | url: 'http://cool-stuff.com/api.json',
44 | dataType: 'jsonp',
45 | success: function(data) {
46 | console.log(data);
47 | }
48 | });
49 | ```
50 |
51 | Safety First! There’s a reason browsers don’t like you talking to other servers - you never know what those servers will send back! Use good data validation, even if the data is “safe.”
52 |
53 | You can only use JSONP for get requests. You can use normal AJAX to do post and delete and all data manipulations, but you cannot do this with JSONP. The practical reason for this is that HTML tags only ever get information, they can’t do anything else (think image tags, links for style sheets, and script tags). The handy reason is that if you owned the API you almost certainly would not want randoms from the internet updating your data.
54 |
--------------------------------------------------------------------------------
/javascript/dataTypes.md:
--------------------------------------------------------------------------------
1 | ## What data types are supported in Javascript?
2 |
3 | According to the latest ECMAScript release, these are the data types:
4 |
5 | Boolean
6 | Null
7 | Undefined
8 | Number
9 | String
10 | Symbol
11 | Object
12 | Ok, let’s run over those one by one:
13 |
14 | Boolean
15 | Pretty standard across all languages, booleans are true and false. They're often used for conditional statements.
16 |
17 | var raining = false;
18 | if(raining) {
19 | bringUmbrella();
20 | }
21 |
22 | Null and Undefined
23 |
24 | In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:
25 | ```js
26 | var TestVar;
27 | alert(TestVar); //shows undefined
28 | alert(typeof TestVar); //shows undefined
29 | ```
30 | null is an assignment value. It can be assigned to a variable as a representation of no value:
31 | ```js
32 | var TestVar = null;
33 | alert(TestVar); //shows null
34 | alert(typeof TestVar); //shows object
35 | ```
36 | From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.
37 | ```js
38 | null === undefined // false
39 | null == undefined // true
40 | null === null // true
41 | ```
42 | Number
43 | Things start to get more interesting here. The number data type covers integers and floats. That is, the number type can handle normal numbers (1, 2, 3, 4), but also negative numbers and decimal places. This is different from many languages that have multiple data types to support different numbers.
44 | ```js
45 | var num = 1;
46 | typeof num; // number
47 |
48 | var num = -2;
49 | typeof num; // number
50 |
51 | var num = 0.3;
52 | typeof num; // number
53 | ```
54 | String
55 | As in most languages, JS strings are groupings of characters.
56 | ```js
57 | "hello world";
58 | "I like cats";
59 | 'Testing "quotes';
60 | ```
61 | I don’t think they're particularly interesting, but they are remarkably powerful. The main way we communicate with our users is the written word and string makes this possible.
62 |
63 | Symbol
64 | This is new in ECMAScript 6; check the browser support before you use it.
65 |
66 | Symbols allow for private(ish) properties on objects. Before ECMAScript 6 all properties for an object could be accessed through for in, like this:
67 | ```js
68 | var dog = { bark: true }
69 |
70 | for (var property in dog) {
71 | if (dog.hasOwnProperty(property)) {
72 | console.log(property); // logs "bark"
73 | }
74 | }
75 | ```
76 | Since symbols are not enumerable they cannot be accessed in this way. However, the symbolised properties are not truly private since they can be accessed directly.
77 | ```js
78 | var breed = Symbol("breed");
79 | var dog = { bark: true };
80 | dog[breed] = "Corgi";
81 |
82 | for (var property in dog) {
83 | if (dog.hasOwnProperty(property)) {
84 | console.log(property); // logs "bark", but not "breed"
85 | }
86 | }
87 | console.log(dog[breed]); // logs "Corgi"
88 | ```
89 | Object
90 | Everything in JS that we didn’t discuss above is an Object. So objects are the most complex data type; I'll dedicate a future post to them since it’s a lot to cover here. But you've probably worked with objects in the past. They typically look like this:
91 | ```js
92 | var cat = { sound: "meow" };
93 |
94 | var fluffy = new Cat();
95 |
96 | var whiskers = new function() {
97 | this.sound = "meow";
98 | }
99 | ```
100 | But notice that we haven’t mentioned Array, Date, or even function that’s because, officially, they're all of type object.
101 |
--------------------------------------------------------------------------------
/javascript/problems/battleshipField.md:
--------------------------------------------------------------------------------
1 | ## Battleship field validator
2 |
3 | Write a method that takes a field for well-known board game "Battleship" as an argument and returns true if it has a valid disposition of ships, false otherwise. Argument is guaranteed to be 10*10 two-dimension array. Elements in the array are numbers, 0 if the cell is free and 1 if occupied by ship.
4 |
5 | Battleship (also Battleships or Sea Battle) is a guessing game for two players. Each player has a 10x10 grid containing several "ships" and objective is to destroy enemy's forces by targetting individual cells on his field. The ship occupies one or more cells in the grid. Size and number of ships may differ from version to version. In this kata we will use Soviet/Russian version of the game.
6 |
7 |
8 | Before the game begins, players set up the board and place the ships accordingly to the following rules:
9 | * There must be single battleship (size of 4 cells), 2 cruisers (size 3), 3 destroyers (size 2) and 4 submarines (size 1). Any additional ships are not allowed, as well as missing ships.
10 | * Each ship must be a straight line, except for submarines, which are just single cell.
11 | * The ship cannot overlap or be in contact with any other ship, neither by edge nor by corner.
12 |
13 | ### Solution
14 |
15 | ```js
16 | function validateBattlefield(field) {
17 | let m = 0, n = 0;
18 | let k = 0;
19 | const ships = [Infinity, 3, 2, 1]
20 | maxShip = () => ships.filter(ship=>ship).length
21 | for (let i = 0; i < 10; i++) {
22 | for (let j = 0; j < 10; j++) {
23 |
24 | if (!field[j][i] || j == 9) {
25 | if (n != 0) {
26 | if (maxShip() < n) return false
27 | ships[n - 1]--
28 | n = 0
29 | }
30 | } else {
31 | n++
32 | if (n > maxShip) {
33 | return false
34 | }
35 | }
36 | if (!field[i][j] || i == 9) {
37 | if (m != 0) {
38 | if (maxShip() < m) return false
39 | ships[m - 1]--
40 | m = 0
41 | }
42 | } else {
43 | try {
44 | if (m > maxShip || !!field[i + 1][j + 1] || !!field[i + 1][j - 1]) {
45 | return false
46 | }
47 | } catch(e) {}
48 | m++
49 | k++
50 | }
51 | }
52 | }
53 | return k === 4 + 3 * 2 + 2 * 3 + 4 && maxShip() == 1
54 | }
55 | ```
56 |
57 | ### Nicer
58 |
59 | ```js
60 | function validateBattlefield(field) {
61 | var hit = (row, col) => (row < 0 || col < 0 || row > 9 || col > 9) ? 0 : field[row][col];
62 | for (var ships = [10,0,0,0,0], row = 0; row < 10; row++) {
63 | for (var col = 0; col < 10; col++) {
64 | if ( hit(row,col) ) {
65 | if ( hit(row-1, col-1) || hit(row-1, col+1) ) return false; // Corner is touching
66 | if ( hit(row-1, col ) && hit(row , col-1) ) return false; // Side is touching
67 | if ( ( field[row][col] += hit(row-1, col) + hit(row, col-1) ) > 4 ) return false; // Ship is too long
68 | ships[field[row][col]]++; ships[field[row][col] - 1]--;
69 | } } }
70 | return [0,4,3,2,1].every((s,i) => s == ships[i]);
71 | }
72 | ```
73 |
74 | ### Shorter
75 |
76 | ```js
77 | function validateBattlefield(field) {
78 | var s = "000000000000", f = s + field.join("0").replace(/,/g, "") + s;
79 | var ships = "4321", h = "0(?=00........010........000)", v = h + "|" + h;
80 | if (/1.{9}(..)?1/.test(f)) return false;
81 | for (var i = 0; i < 10; ++ i) {
82 | if (f.split(new RegExp(v)).length != -~ships[i]) return false;
83 | v = v.replace(/([01])(0)(\.|(?=\)))(?=.*\|)|(01+0\.+)(?!.*1)/g, "$1$1$2$4$4");
84 | }
85 | return true;
86 | }
87 | ```
88 |
--------------------------------------------------------------------------------
/html/README.md:
--------------------------------------------------------------------------------
1 | # HTML Q&As
2 |
3 | ## What does a `doctype` do?
4 |
5 | `DOCTYPE`s are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the `DOCTYPE` in a document ensures that the browser makes a best-effort attempt at following the relevant specifications.
6 | * The doctype declaration should be the very first thing in an HTML document, before the tag.
7 | * The doctype declaration is not an HTML tag; it is an instruction to the web browser about what version of the markup language the page is written in.
8 |
9 | ## `window` vs `document`
10 |
11 | JavaScript has a global object and everything runs under it. window is that global object that holds global variables, global functions, location, history everything is under it. Besides, setTimeout, ajax call (XMLHttpRequest), console or localStorage are part of window.
12 |
13 | document is also under window. document is a property of the window object. document represents the DOM and DOM is the object oriented representation of the html markup you have written. All the nodes are part of document. Hence you can use getElementById or addEventListener on document. These methods are not present in the window object.
14 |
15 | ```js
16 | window.document === document; //true
17 | window.getElementById; //undefined
18 | document.getElementById; //function getElementById() { [native code] }
19 | ```
20 |
21 | ## How `window` and `iframe` relate to each other?
22 |
23 | An iframe actually is considered as a new window with its own document loaded into it. Here is where it may seem a little odd, but does make sense if you think about it. The original, parent window, is responsible for other windows to be loaded, not the document.
24 |
25 | 
26 |
27 | The property to access a frame is `window.frames[]`, which is an array of all the frames. If you only have one iframe you access it by using `window.frames[0]`. Since the iframe is also a window object, accessing window properties of that frame is done by using `window.frames[0].mywindowproperty`.
28 |
29 |
30 | ### HTML5 && HTML 4.01
31 |
32 | Prior to HTML5, the html was SGML based which required a Document Type Defination to establish rules and grammer for markup. Thus, doctype had other information about the Document Type Defination (DTD).
33 |
34 | However, with introduction of HTML5 the DOCTYPE is the only thing needed to enable the STANDARD MODE.
35 |
36 | A DOCTYPE is optional for HTML5 documents in the XHTML syntax (i.e., XHTML5 documents):
37 |
38 | ### Is doctype needed for HTML 5 documents?
39 | A `DOCTYPE` is required for HTML5 documents in the HTML syntax.
40 | XML documents may contain a `DOCTYPE` if desired, but this is not required to conform to this specification.
41 |
42 | #### Exceptions
43 | HTML5 documents in the `srcdoc` attribute of an `iframe` element don’t need a `DOCTYPE`.
44 |
45 |
46 | ## Describe the difference between `
45 |
46 |
47 | ```
48 |
49 | The example above adds shadow DOM to a literal element that has no content. Nothing is displayed yet. Continuing with the same example, you can insert text into the shadow DOM above with code like the following, and it will display in the browser:
50 |
51 | ```js
52 | shadow.innerHTML = '
Here is some new text
';
53 | ```
54 |
55 | ### Styling Shadow DOM
56 |
57 | You use the `';
67 |
68 | ```
69 |
70 | ### HTML file
71 |
72 | ```html
73 | If nothing appeared below, then your browser is not supporting Custom Elements.
74 |
75 |
76 |
77 | ```
78 |
79 | ### JS file
80 |
81 | ```js
82 | // Create a class for the element
83 | class XProduct extends HTMLElement {
84 | constructor() {
85 | // Always call super first in ctor
86 | super();
87 |
88 | // Create a shadow root
89 | var shadow = this.attachShadow({mode: 'open'});
90 |
91 | // Create a standard img element and set it's attributes.
92 | var img = document.createElement('img');
93 | img.alt = this.getAttribute('data-name');
94 | img.src = this.getAttribute('data-img');
95 | img.width = '150';
96 | img.height = '150';
97 | img.className = 'product-img';
98 |
99 | // Add the image to the shadow root.
100 | shadow.appendChild(img);
101 |
102 | // Add an event listener to the image.
103 | img.addEventListener('click', () => {
104 | window.location = this.getAttribute('data-url');
105 | });
106 |
107 | // Create a link to the product.
108 | var link = document.createElement('a');
109 | link.innerText = this.getAttribute('data-name');
110 | link.href = this.getAttribute('data-url');
111 | link.className = 'product-name';
112 |
113 | // Add the link to the shadow root.
114 | shadow.appendChild(link);
115 | }
116 | }
117 |
118 | // Define the new element
119 | customElements.define('x-product', XProduct);
120 | ```
121 |
122 | ### CSS file:
123 |
124 | ```css
125 | body {
126 | background: #F7F7F7;
127 | }
128 |
129 | x-product {
130 | display: inline-block;
131 | float: left;
132 | margin: 0.5em;
133 | border-radius: 3px;
134 | background: #FFF;
135 | box-shadow: 0 1px 3px rgba(0,0,0,0.25);
136 | font-family: Helvetica, arial, sans-serif;
137 | -webkit-font-smoothing: antialiased;
138 | }
139 |
140 | x-product::slotted(.product-img) {
141 | cursor: pointer;
142 | background: #FFF;
143 | margin: 0.5em;
144 | }
145 |
146 | x-product::slotted(.product-name) {
147 | display: block;
148 | text-align: center;
149 | text-decoration: none;
150 | color: #08C;
151 | border-top: 1px solid #EEE;
152 | font-weight: bold;
153 | padding: 0.75em 0;
154 | }
155 | ```
156 |
--------------------------------------------------------------------------------
/patterns/mediator.md:
--------------------------------------------------------------------------------
1 | The Mediator Pattern
2 | The mediator pattern is best introduced with a simple analogy - think of your typical airport traffic control. The tower handles what planes can take off and land because all communications are done from the planes to the control tower, rather than from plane-to-plane. A centralized controller is key to the success of this system and that's really what a mediator is.
3 |
4 | Mediators are used when the communication between modules may be complex, but is still well defined. If it appears a system may have too many relationships between modules in your code, it may be time to have a central point of control, which is where the pattern fits in.
5 | In real-world terms, a mediator encapsulates how disparate modules interact with each other by acting as an intermediary. The pattern also promotes loose coupling by preventing objects from referring to each other explicitly - in our system, this helps to solve our module inter-dependency issues.
6 |
7 | What other advantages does it have to offer? Well, mediators allow for actions of each module to vary independently, so it’s extremely flexible. If you've previously used the Observer (Pub/Sub) pattern to implement an event broadcast system between the modules in your system, you'll find mediators relatively easy to understand.
8 |
9 | Let's take a look at a high level view of how modules might interact with a mediator:
10 |
11 | 
12 |
13 | Consider modules as publishers and the mediator as both a publisher and subscriber. Module 1 broadcasts an event notifying the mediator something needs to done. The mediator captures this message and 'starts' the modules needed to complete this task Module 2 performs the task that Module 1 requires and broadcasts a completion event back to the mediator. In the mean time, Module 3 has also been started by the mediator and is logging results of any notifications passed back from the mediator.
14 |
15 | Notice how at no point do any of the modules directly communicate with one another. If Module 3 in the chain were to simply fail or stop functioning, the mediator could hypothetically 'pause' the tasks on the other modules, stop and restart Module 3 and then continue working with little to no impact on the system. This level of decoupling is one of the main strengths the pattern has to offer.
16 |
17 | To review, the advantages of the mediator are that:
18 |
19 | It decouples modules by introducing an intermediary as a central point of control.It allows modules to broadcast or listen for messages without being concerned with the rest of the system. Messages can be handled by any number of modules at once.
20 |
21 | It is typically significantly more easy to add or remove features to systems which are loosely coupled like this.
22 |
23 | And its disadvantages:
24 |
25 | By adding a mediator between modules, they must always communicate indirectly. This can cause a very minor performance drop - because of the nature of loose coupling, its difficult to establish how a system might react by only looking at the broadcasts. At the end of the day, tight coupling causes all kinds of headaches and this is one solution.
26 |
27 |
28 | Example: This is a possible implementation of the mediator pattern based on previous work by @rpflorence
29 |
30 | ```js
31 | var mediator = (function(){
32 | var subscribe = function(channel, fn){
33 | if (!mediator.channels[channel]) mediator.channels[channel] = [];
34 | mediator.channels[channel].push({ context: this, callback: fn });
35 | return this;
36 | },
37 |
38 | publish = function(channel){
39 | if (!mediator.channels[channel]) return false;
40 | var args = Array.prototype.slice.call(arguments, 1);
41 | for (var i = 0, l = mediator.channels[channel].length; i < l; i++) {
42 | var subscription = mediator.channels[channel][i];
43 | subscription.callback.apply(subscription.context, args);
44 | }
45 | return this;
46 | };
47 |
48 | return {
49 | channels: {},
50 | publish: publish,
51 | subscribe: subscribe,
52 | installTo: function(obj){
53 | obj.subscribe = subscribe;
54 | obj.publish = publish;
55 | }
56 | };
57 |
58 | }());
59 | ```
60 |
61 | Example: Here are two sample uses of the implementation from above. It's effectively managed publish/subscribe:
62 |
63 | ```js
64 | //Pub/sub on a centralized mediator
65 |
66 | mediator.name = "tim";
67 | mediator.subscribe('nameChange', function(arg){
68 | console.log(this.name);
69 | this.name = arg;
70 | console.log(this.name);
71 | });
72 |
73 | mediator.publish('nameChange', 'david'); //tim, david
74 |
75 |
76 | //Pub/sub via third party mediator
77 |
78 | var obj = { name: 'sam' };
79 | mediator.installTo(obj);
80 | obj.subscribe('nameChange', function(arg){
81 | console.log(this.name);
82 | this.name = arg;
83 | console.log(this.name);
84 | });
85 |
86 | obj.publish('nameChange', 'john'); //sam, john
87 | ```
88 |
89 | The mediator plays the role of the application core. We've briefly touched on some of its responsibilities but lets clarify what they are in full.
90 |
91 | The core's primary job is to manage the module lifecycle. When the core detects an interesting message it needs to decide how the application should react - this effectively means deciding whether a module or set of modules needs to be started or stopped.
92 |
93 | Once a module has been started, it should ideally execute automatically. It's not the core's task to decide whether this should be when the DOM is ready and there's enough scope in the architecture for modules to make such decisions on their own.
94 | You may be wondering in what circumstance a module might need to be 'stopped' - if the application detects that a particular module has failed or is experiencing significant errors, a decision can be made to prevent methods in that module from executing further so that it may be restarted. The goal here is to assist in reducing disruption to the user experience.
95 |
96 | In addition, the core should enable adding or removing modules without breaking anything. A typical example of where this may be the case is functionality which may not be available on initial page load, but is dynamically loaded based on expressed user-intent eg. Google could keep the chat widget collapsed by default and only dynamically load in the chat module(s) when a user expresses an interest in using that part of the application. From a performance optimization perspective, this may make sense.
97 |
98 | Error management will also be handled by the application core. In addition to modules broadcasting messages of interest they will also broadcast any errors experienced which the core can then react to accordingly (eg. stopping modules, restarting them etc).It's important that as part of a decoupled architecture there to be enough scope for the introduction of new or better ways of handling or displaying errors to the end user without manually having to change each module. Using publish/subscribe through a mediator allows us to achieve this.
99 |
--------------------------------------------------------------------------------
/javascript/problems/maybeMonad.md:
--------------------------------------------------------------------------------
1 | ## Implement Maybe modan
2 |
3 | I find the `Maybe` monad to be the easiest one to wrap my head around. Thus, it is the first in what may be a series of katas about monads.
4 |
5 | Every monad must support two operations:
6 |
7 | - `return` or `unit` which takes a value and wraps it in whatever container the monad needs it to be wrapped in
8 | - `bind` (called `>>=` in Haskell) which takes a function and returns a function.
9 | The input function to bind is a function that takes a value (not in the monad) as an argument and returns a value in the monad. The output function from bind is a function that takes a value in the monad and returns a value in the monad.
10 |
11 | Note: Technically, the input function can take a value not in the monad to a value in any monad and bind would return a function that takes a value in this monad and returns a value in whatever monad the input function returned a value in. It is hard to really get the benefits of doing that in a weakly-typed language like Coffeescript so for this kata there will only be one monad.
12 |
13 | There are some laws that dictate how unit and bind must compose. Here is what the monad laws look like in Coffeescript or Javascript (where f and g are functions that take a value argument and return a monad value):
14 |
15 | ```js
16 | bind(f)(unit(x)) === f(x) // for any value x (left identity)
17 | bind(unit)(x) === x // for any value x (right identity)
18 | bind(g)(bind(f)(m)) ===
19 | bind( function (x) { return bind(g)(f(x)); } )(m) // for any m in the monad (associativity)
20 | ```
21 | Sorting all of that out is tough. Remember that bind returns a function that takes monad values to monad values. For example, the last line asserts that both of the following functions always return the same thing as long as m is a valid monad value, f is a function from values to values in the monad, and g is a function from values to values in the monad:
22 |
23 | ```js
24 | function lhs(m,f,g) {
25 | var bg = bind(g);
26 | var bf = bind(f);
27 | return bg(bf(m));
28 | }
29 |
30 | function rhs(m,f,g) ->
31 | var bg = bind(g);
32 | var ba = bind( function (x) { return bg(f(x)); } );
33 | return ba(m);
34 | }
35 | ```
36 |
37 | You probably don't need to completely understand the above to succeed in this kata.
38 |
39 | ### Other monad operations
40 |
41 | For convenience, monads often support a lift function which takes a function from values to values and returns a function from values to the monad values.
42 |
43 | Our monads will also support a do function which takes a monad value and an arbitrary number of functions (which take a value as an argument and return a monad value). The do function binds the first function with the monad and passes it the argument value. It then uses the return value of that first bound function as the input for the next function, etc. It finally returns the last result. So, for example: do(m, f, g, h) should be equivalent to:
44 | ```js
45 | var bf = bind(f);
46 | var bg = bind(g);
47 | var bh = bind(h);
48 | bh(bg(bf(m)));
49 | ```
50 |
51 | ### The Maybe monad
52 |
53 | The Maybe monad has two types of values Just x and Nothing values. These classes are already written here.
54 |
55 | ```js
56 | function Just (x) {
57 | this.toString = function () { return "Just " + x.toString(); };
58 | this.just = x;
59 | Object.freeze(this);
60 | };
61 | Just.prototype = new Maybe();
62 | Just.prototype.constructor = Just;
63 |
64 | function Nothing () {
65 | this.toString = function () { return "Nothing"; };
66 | Object.freeze(this);
67 | };
68 | Nothing.prototype = new Maybe();
69 | Nothing.prototype.constructor = Nothing;
70 | You need to fill in the class methods on the Maybe class:
71 |
72 | Maybe.unit = function (x) { ... };
73 | Maybe.bind = function (f) { ... };
74 | Maybe.lift = function (f) { ... };
75 | Maybe.do = function (m,fns) { ... };
76 | ```
77 | Here's a graphical depiction of how @lift and @bind are related:
78 |
79 | The `@unit` function should return a Maybe subclass instance which wraps the value x:
80 |
81 | ```js
82 | Maybe.unit(x) instanceof Maybe // => true
83 | ```
84 | The @bind function should take the function f which has a single input argument value and returns a Maybe subclass instance. The @bind function should return a new function which takes one Maybe subclass instance as an argument. If the argument is Just x, then the returned function should return (f x). If the argument is Nothing, then the returned function should return Nothing. If the argument is not a Maybe subclass instance, then the returned function should throw an error.
85 |
86 | ```js
87 | function mDup(str) {
88 | return new Just(str+str);
89 | }
90 | mDup("abc"); // => new Just("abcabc")
91 |
92 | var bmDup = Maybe.bind(mDup);
93 | bmDup(new Nothing) // => new Nothing
94 | bmDup(new Just("abc")) // => new Just("abcabc")
95 | ```
96 |
97 | The @lift function should take the function f which has a single input argument value and returns a value. The @lift function should return a new function of a single argument x that wraps the results of (f x) in a Maybe subclass instance. If evaluation of (f x) throws an exception of any kind, then this function should return a Nothing instances, otherwise it should return a Just instance containing (f x).
98 |
99 | ```js
100 | function nonnegative(x) {
101 | if (isNaN(x) || 0 <= x) {
102 | return x;
103 | } else {
104 | throw "Argument " + x + " must be non-negative";
105 | }
106 | }
107 | var mNonnegative = Maybe.lift(nonnegative)
108 |
109 | mNonnegative(2) // => new Just 2
110 | mNonnegative(-1) // => new Nothing
111 | mNonnegative(undefined) // => new Just undefined
112 | ```
113 |
114 | The @do function should take a Maybe subclass instance m and a sequence of functions, bind each of the functions using @bind, call the first bound function, pass that value to the second bound function, etc. and return the final function's return value.
115 |
116 | ```js
117 | var mDup = Maybe.lift( function (s) { return s+s; } );
118 | var mTrim = Maybe.lift( function (s) { return s.replace(/\s+$/, ''); } );
119 |
120 | Maybe.do( Maybe.unit("abc "), mDup, mTrim, mDup ) // => new Just "abc abcabc abc"
121 | ```
122 |
123 | ## Solution
124 |
125 | ```js
126 | function Maybe () {
127 | Object.freeze(this);
128 | }
129 |
130 | Maybe.unit = x => (
131 | typeof x !== 'undefined' ? new Just(x): new Nothing()
132 | )
133 |
134 | Maybe.bind = f => x => {
135 | if (!(x instanceof Maybe)) {
136 | throw new Error('boom')
137 | }
138 |
139 | return x instanceof Nothing ? x : f(x.just)
140 | }
141 |
142 | Maybe.lift = f => x => {
143 | try {
144 | return new Just(f(x))
145 | } catch (err) {
146 | return new Nothing()
147 | }
148 | }
149 |
150 | Maybe.do = (x, ...fns) => (
151 | fns.reduce((prev, f) => Maybe.bind(f)(prev), x)
152 | )
153 |
154 | function Just (x) {
155 | this.toString = () => `Just ${x.toString()}`
156 | this.just = x
157 | Object.freeze(this)
158 | }
159 | Just.prototype = new Maybe()
160 | Just.prototype.constructor = Just
161 |
162 |
163 | function Nothing () {
164 | this.toString = () => "Nothing"
165 | Object.freeze(this)
166 | }
167 | Nothing.prototype = new Maybe()
168 | Nothing.prototype.constructor = Nothing
169 | ```
170 |
--------------------------------------------------------------------------------