Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikhail-hud committed Feb 23, 2021
0 parents commit 82a664b
Show file tree
Hide file tree
Showing 130 changed files with 46,483 additions and 0 deletions.
14 changes: 14 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
The code in this repo is Copyright © 2020 by David Flanagan but is free for
everyone to use. O'Reilly's standard permission notice appears in the
book's preface:

> This book is here to help you get your job done. In general, if
> example code is offered with this book, you may use it in your
> programs and documentation. You do not need to contact us for
> permission unless you’re reproducing a significant portion of the
> code. For example, writing a program that uses several chunks of code
> from this book does not require permission. Selling or distributing
> examples from O’Reilly books does require permission. Answering a
> question by citing this book and quoting example code does not require
> permission. Incorporating a significant amount of example code from
> this book into your product’s documentation does require permission.
221 changes: 221 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
# Example code from _JavaScript: The Definitive Guide_

![The cover of JavaScript: The Definitive Guide](smallcover.jpg)

This repo includes all of the numbered examples from the 7th edition
of my book, plus many unnumbered examples as well. In general, if an
unnumbered example defines a function that seems like it might be
useful to someone, I've included it here. The code is listed below in
roughly the same order as in the book. To locate code, just look below
for the example number or section number that the code appears in.

This code is far more useful when studied in the context of the book
in which it appears, and I'd ask you to [please buy yourself a
copy](https://amzn.to/3fTETLV) if you are able to. These examples are
[free for everyone to use](LICENSE.md).

If you discover problems with this repo, or bugs in the code, please
open a GitHub issue. (Note, however, that I will not accept pull
requests because I need to maintain clear copyright to the code so
that I can use it in future editions of the book.)


## Chapter 1: Introduction to JavaScript
- [Example 1-1](ch01/charfreq.js): Computing character frequency histograms with JavaScript

## Chapter 3: Types, Values, and Variables

- [§3.10.3](ch03/destructuring.js): Destructuring Assignment

## Chapter 6: Objects

- [§6.7](ch06/merge.js): Extending Objects
- §6.10.6: Property Getters and Setters
- [serialnum.js](ch06/serialnum.js)
- [random.js](ch06/random.js)

## Chapter 7: Arrays

- [§7.8.6](ch07/findall.js): Array Searching and Sorting Methods
- [§7.9](ch07/isArrayLike.js): Array-Like Objects

## Chapter 8: Functions

- [§8.1](ch08/example_functions.js): Defining Functions
- [§8.3.4](ch08/timed.js): The Spread Operator for Function Calls
- [§8.3.5](ch08/arraycopy.js): Destructuring Function Arguments into Parameters
- [Example 8-1](ch08/operators.js): Using functions as data
- §8.4.1 Defining Your Own Function Properties
- [uniqueInteger](ch08/uniqueInteger.js)
- [factorial](ch08/factorial.js)
- §8.6 Closures
- [uniqueInteger2](ch08/uniqueInteger2.js)
- [counter](ch08/counter.js)
- [counter 2](ch08/counter2.js)
- [Example 8-2](ch08/addPrivateProperty.js): Private property accessor methods using closures
- [§8.7.4](ch08/trace.js): The call() and apply() Methods
- §8.8.1: Processing Arrays with Functions
- [stats1](ch08/stats1.js)
- [stats2](ch08/stats2.js)
- [stats3](ch08/stats3.js)
- §8.8.2: Higher-Order Functions
- [not](ch08/not.js)
- [mapper](ch08/mapper.js)
- [compose](ch08/compose.js)
- [§8.8.3](ch08/partial.js): Partial Application of Functions
- [§8.8.4](ch08/memoize.js): Memoization

## Chapter 9: Classes

- [Example 9-1](ch09/range1.js): A simple JavaScript class
- [Example 9-2](ch09/range2.js): A Range class using a constructor
- [Example 9-3](ch09/range3.js): The Range class rewritten using _class_
- [Example 9-4](ch09/Complex.js): Complex.js: a complex number class
- [Example 9-5](ch09/Span.js): Span.js: a simple subclass of Range
- §9.5.2: Subclasses with extends and super
- [EZArray](ch09/EZArray.js)
- [Example 9-6](ch09/TypedMap.js): TypedMap.js: a subclass of Map that checks key and value types
- [Example 9-7](ch09/Histogram.js): Histogram.js: a Set-like class implemented with delegation
- [Example 9-8](ch09/Sets.js): Sets.js: a hierarchy of abstract and concrete set classes

## Chapter 10: Modules

- §10.1: Modules with Classes, Objects, and Closures
- [BitSet](ch10/BitSet.js)
- [stats](ch10/stats.js)

## Chapter 11: The JavaScript Standard Library

- [§11.2.3](ch11/sieve.js): Using Typed Arrays
- [§11.2.5](ch11/littleEndian.js): DataView and Endianness

## Chapter 12: Iterators and Generators

- [Example 12-1](ch12/Range.js): An iterable numeric Range class
- §12.2: Implementing Iterable Objects
- [map](ch12/map.js)
- [filter](ch12/filter.js)
- [words](ch12/words.js)
- §12.3.1: Generator Examples
- [fibonacciSequence](ch12/fibonacciSequence.js)
- [take](ch12/take.js)
- [zip](ch12/zip.js)
- §12.3.2 yield* and Recursive Generators
- [sequence](ch12/sequence.js)

## Chapter 13: Asynchronous JavaScript

- §13.1.4: Callbacks and Events in Node
- [getText](ch13/getText.js)
- §13.2.6: Making Promises
- [wait](ch13/wait.js)
- [Example 13-1](ch13/getJSON.js): An asynchronous getJSON() function
- §13.2.7 Promises in Sequence
- [fetchSequentially](ch13/fetchSequentially.js)
- [promiseSequence](ch13/promiseSequence.js)
- §13.4.3: Asynchronous Generators
- [clock1](ch13/clock1.js)
- §13.4.4: Implementing Asynchronous Iterators
- [clock2](ch13/clock2.js)
- [AsyncQueue](ch13/AsyncQueue.js)

## Chapter 14: Metaprogramming

- [Example 14-1](ch14/assignDescriptors.js): Copying properties and their attributes from one object to another
- §14.4.3: Symbol.toStringTag
- [classof](ch14/classof.js)
- §14.4.6: Pattern-Matching Symbols
- [Glob](ch14/Glob.js)
- §14.5: Template Tags
- [html](ch14/html.js)
- [glob](ch14/globtag.js)
- §14.7: Proxy Objects
- [identity](ch14/identity.js)
- [readOnlyProxy](ch14/readOnlyProxy.js)
- [loggingProxy](ch14/loggingProxy.js)

## Chapter 15: JavaScript in Web Browsers

- §15.1.1: JavaScript in HTML <script> Tags
- [digital clock](ch15/digital_clock.html)
- [importScript](ch15/importScript.js)
- §15.2.2: Registering Event Handlers
- [onload](ch15/onload.js)
- §15.3.2: Document Structure and Traversal
- [traverse](ch15/traverse.js)
- [textContent](ch15/textContent.js)
- [Example 15-1](ch15/TOC.js): Generating a table of contents with the DOM API
- §15.4.4: Scripting Stylesheets
- [setTheme](ch15/setTheme.js)
- [Example 15-2](ch15/inline-circle.js): The <inline-circle> custom element
- [Example 15-3](ch15/search-box.js): Implementing a web component
- §15.7.1: SVG in HTML
- [clock face](ch15/clock.html)
- §15.7.2: Scripting SVG
- [clock motion](ch15/clock.js)
- [Example 15-4](ch15/pieChart.js): Drawing a pie chart with JavaScript and SVG
- [Example 15-5](ch15/polygons.js): Regular polygons with moveTo(), lineTo(), and closePath()
- [Example 15-6](ch15/curves.js): Adding curves to a path
- §15.8.5: Coordinate System Transforms
- [shear() and rotateAbout()](ch15/transforms.js)
- [Example 15-7](ch15/koch.js): A Koch snowflake with transformations
- [§15.8.6](ch15/clip.js): Clipping
- [Example 15-8](ch15/smear.js): Motion blur with ImageData
- [§15.9.2](ch15/webaudio.js): The WebAudio API
- [Example 15-9](ch15/guessinggame.html): History management with pushState()
- §15.11.1: fetch()
- [error handling](ch15/fetchWithErrorHandling.js)
- [request parameters](ch15/settingRequestParameters.js)
- [request headers](ch15/settingRequestHeaders.js)
- [file upload](ch15/uploadCanvasImage.js)
- [with timeout](ch15/fetchWithTimeout.js)
- [Example 15-10](ch15/streamBody.js): Streaming the response body from a fetch() request
- [Example 15-11](ch15/chatClient.html): A simple chat client using EventSource
- [Example 15-12](ch15/chatServer.js): A Server Sent Events chat server
- §15.12.2: Cookies
- [getCookies](ch15/getCookies.js)
- [setCookie](ch15/setCookie.js)
- [Example 15-13](ch15/zipcodeDatabase.js): A IndexedDB database of US postal codes
- [zipcode data](ch15/zipcodes.json)
- [test program](ch15/zipcodes.html)
- [Example 15-14](ch15/mandelbrotWorker.js): Worker code for computing regions of the Mandelbrot set
- [Example 15-15](ch15/mandelbrot.js): A web application for displaying and exploring the Mandelbrot set
- [mandelbrot.html](ch15/mandelbrot.html)

## Chapter 16: Server-Side JavaScript with Node

- §16.2: Node Is Asynchronous by Default
- [readConfigFile](ch16/readConfigFile.js)
- [readConfigFile2](ch16/readConfigFile2.js)
- [readConfigFile3](ch16/readConfigFile3.js)
- [readConfigFileSync](ch16/readConfigFileSync.js)
- §16.5.1: Pipes
- [pipe](ch16/pipe.js)
- [gzip](ch16/gzip.js)
- [grep](ch16/grep.js)
- §16.5.2: Asynchronous Iteration
- [asyncgrep](ch16/asyncgrep.js)
- §16.5.3: Writing to Streams and Handling Backpressure
- [write](ch16/write.js)
- [copy](ch16/copy.js)
- §16.5.4: Reading Streams with Events
- [copyfile](ch16/copyfile.js)
- [hash](ch16/hash.js)
- §16.7.6: Working with Directories
- [listDirectory](ch16/listDirectory.js)
- §16.8 HTTP: Clients and Servers
- [postJSON](ch16/postJSON.js)
- [staticHTTPServer](ch16/staticHTTPServer.js)
- §16.9: Non-HTTP Network Servers and Clients
- [knockKnockServer](ch16/knockKnockServer.js)
- [knockKnockClient](ch16/knockKnockClient.js)
- §16.10.2: exec() and execFile()
- [parallelExec](ch16/parallelExec.js)
- §16.10.4: fork()
- [parent](ch16/parent.js)
- [child](ch16/child.js)
- §16.11.1: Creating Workers and Passing Messages
- [splines](ch16/splines.js)
- §16.11.5: Sharing Typed Arrays Between Threads
- [incorrect parallel increment](ch16/parallelIncrement.js)
- [atomic increment](ch16/atomicIncrement.js)
96 changes: 96 additions & 0 deletions ch01/charfreq.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/**
* This Node program reads text from standard input, computes the frequency
* of each letter in that text, and displays a histogram of the most
* frequently used characters. It requires Node 12 or higher to run.
*
* In a Unix-type environment you can invoke the program like this:
* node charfreq.js < corpus.txt
*/

// This class extends Map so that the get() method returns the specified
// value instead of null when the key is not in the map
class DefaultMap extends Map {
constructor(defaultValue) {
super(); // Invoke superclass constructor
this.defaultValue = defaultValue; // Remember the default value
}

get(key) {
if (this.has(key)) { // If the key is already in the map
return super.get(key); // return its value from superclass.
}
else {
return this.defaultValue; // Otherwise return the default value
}
}
}

// This class computes and displays letter frequency histograms
class Histogram {
constructor() {
this.letterCounts = new DefaultMap(0); // Map from letters to counts
this.totalLetters = 0; // How many letters in all
}

// This function updates the histogram with the letters of text.
add(text) {
// Remove whitespace from the text, and convert to upper case
text = text.replace(/\s/g, "").toUpperCase();

// Now loop through the characters of the text
for(let character of text) {
let count = this.letterCounts.get(character); // Get old count
this.letterCounts.set(character, count+1); // Increment it
this.totalLetters++;
}
}

// Convert the histogram to a string that displays an ASCII graphic
toString() {
// Convert the Map to an array of [key,value] arrays
let entries = [...this.letterCounts];

// Sort the array by count, then alphabetically
entries.sort((a,b) => { // A function to define sort order.
if (a[1] === b[1]) { // If the counts are the same
return a[0] < b[0] ? -1 : 1; // sort alphabetically.
} else { // If the counts differ
return b[1] - a[1]; // sort by largest count.
}
});

// Convert the counts to percentages
for(let entry of entries) {
entry[1] = entry[1] / this.totalLetters*100;
}

// Drop any entries less than 1%
entries = entries.filter(entry => entry[1] >= 1);

// Now convert each entry to a line of text
let lines = entries.map(
([l,n]) => `${l}: ${"#".repeat(Math.round(n))} ${n.toFixed(2)}%`
);

// And return the concatenated lines, separated by newline characters.
return lines.join("\n");
}
}

// This async (Promise-returning) function creates a Histogram object,
// asynchronously reads chunks of text from standard input, and adds those chunks to
// the histogram. When it reaches the end of the stream, it returns this histogram
async function histogramFromStdin() {
process.stdin.setEncoding("utf-8"); // Read Unicode strings, not bytes
let histogram = new Histogram();
for await (let chunk of process.stdin) {
histogram.add(chunk);
}
return histogram;
}

// This one final line of code is the main body of the program.
// It makes a Histogram object from standard input, then prints the histogram.
histogramFromStdin().then(histogram => { console.log(histogram.toString()); });


39 changes: 39 additions & 0 deletions ch02/charfreq.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//smile
console.log('\u{1F600}');
Math.pow(2, 53); // 9007199254740992, 2 в степени 53.
Math.round(0.6); //1, округляет до ближайшего целого.
Math.ceil(0.6); // 1, округляет в большую сторону до целого
Math.floor(1.6); // 1, округляет в меньшую сторону до целого
Math.abs(-5); // 5 абсолютная величина
Math.max(x, y, z); // возвращает наибольший аргумент
Math.min(x, y, z); // возвращает найменьший аргумент
Math.random(); // псевдослучайное число х, где 0 <= x < 1.0 (от 0 до 1(не включительно))
Math.sqrt(3); // квадратный корень из 3
Math.pow(3, 1 / 3); // кубический корень из 3
Math.trunc(3.9); // 3 преобразует в целое число отбрасывая дробную часть

let s = 'Hello, World';
s[0]; // 'H'
s[s.length - 1]; // 'd'
s.slice(1, 4); // ell
s.slice(-3); // rld
s.split(', '); //["Hello", "World"] разбивает по строке разделителя
s.indexOf('1'); // 2, позиция певой буквы l
s.indexOf('1', 3); // 3, позиция первой буквы l начиная с 3-й позиции
s.startsWith('Hello'); // true
s.endsWith('rld'); // true
s.includes('ll'); // ture

'x'.padStart(3); // " x" добавляет пробел слева до длины 3
'x'.padEnd(3); // "x "добавляет пробел справа до длины 3
'x'.padStart(3, '*'); // "**x" добавляет * слева до длины 3
'x'.padEnd(3, '-'); // "x--"добавляет - справа до длины 3

if (0) {
console.log('text'); // только если 0 !== null или undefined
}

if ((x === 0 && y === 0) || !(z === 0)) {
// x и y равны 0 или z не равно 0
}

Loading

0 comments on commit 82a664b

Please sign in to comment.