Monthly Archives: November 2014

Object-oriented design

An object contains encapsulated data and procedures grouped together to represent an entity. The ‘object interface’, how the object can be interacted with, is also defined. An object-oriented program is described by the interaction of these objects. Object-oriented design is the discipline of defining the objects and their interactions to solve a problem that was identified and documented during object-oriented analysis.

Object-oriented design is a method of design encompassing the process of object-oriented decomposition and a notation for depicting both logical and physical as well as state and dynamic models of the system under design.

http://en.wikipedia.org/wiki/Object-oriented_design
http://en.wikipedia.org/wiki/GRASP_(object-oriented_design)

The Event-Driven Programming Model

In the old days, computer programs often ran in batch mode – they read in a batch of data, did some computation on that data, and then wrote out the results. Later, with time-sharing and text-based terminals, limited kinds of interactivity became possible – the program could ask the user for input, and the user could type in data. The computer could then process the data and display the results on screen.

Nowadays, with graphical displays and pointing devices like mice, the situation is different. Programs are generally event driven; they respond to asynchronous user input in the form of mouse-clicks and keystrokes in a way that depends on the position of the mouse pointer. A web browser is just such a graphical environment. An HTML document contains an embedded graphical user interface (GUI), so client-side JavaScript uses the event-driven programming model.

In client-side JavaScript, the web browser notifies programs of user input by generating events. There are various types of events, such as keystroke events, mouse motion events, and so on. When an event occurs, the web browser attempts to invoke an appropriate event handler function to respond to the event. Thus, to write dynamic, interactive client-side JavaScript programs, we must define appropriate event handlers and register them with the system, so that the browser can invoke them at appropriate times.

In event-driven programming, you write a number of independent (but mutually interacting) event handlers. You do not invoke these handlers directly, but allow the system to invoke them at the appropriate times. Since they are triggered by the user’s input, the handlers will be invoked at unpredictable, asynchronous times. Much of the time, your program is not running at all but merely sitting waiting for the system to invoke one of its event handlers.

Шаблоны проектирования

JavaScript, будучи динамическим нетипизированным языком, опирающимся на использование прототипов, иногда позволяет удивительно легко и даже тривиально реализовать шаблоны проектирования.

Continue reading

Основные приемы и шаблоны JavaScript

  • Снижение количества глобальных переменных, в идеале – не более одной на приложение.
  • Использование единственного объявления var в функциях, что позволяет одним взглядом охватить все переменные и предотвращает появление неожиданностей, вызванных особенностями механизма подъема переменных.
  • Циклы for (использовать только для массивов), циклы for-in (использовать только для объектов), инструкции switch, «eval() – это зло», нежелательность расширения прототипов.
  • Следование соглашениям по оформлению программного кода (последовательное использование пробелов и отступов; использование фигурных скобок и точек с запятой даже там, где они являются необязательными) и соглашениям по именованию (конструкторов, функций и переменных).

Необходимо стремиться свести к минимуму операции обращения к дереву DOM. Это означает, что:

  • Следует избегать обращений к элементам DOM внутри циклов
  • Желательно присваивать ссылки на элементы DOM локальным переменным и работать с этими переменными
  • Следует использовать интерфейс селекторов, где это возможно
  • Следует сохранять значение свойства length в локальной переменной при выполнении итераций через коллекции HTML

Стараться свести к минимуму количество операций, модифицирующих дерево DOM, что означает накапливать изменения, выполняя их за пределами «живого» дерева DOM документа.

Sorting Algorithms

1. Selection sort
・In iteration i, find index min of smallest remaining entry.
・Swap a[i] and a[min].

i min 0 1 2 3 4 5 6 7 8 9 10
S O R T E X A M P L E
0 6 S O R T E X A M P L E
1 4 A O R T E X S M P L E
2 10 A E R T O X S M P L E
3 9 A E E T O X S M P L R
4 7 A E E L O X S M P T R
5 7 A E E L M X S O P T R
6 8 A E E L M O S X P T R
7 10 A E E L M O P X S T R
8 8 A E E L M O P R S T X
9 9 A E E L M O P R S T X
10 10 A E E L M O P R S T X
A E E L M O P R S T X

2. Insertion sort
・In iteration i, swap a[i] with each larger entry to its left.

i j 0 1 2 3 4 5 6 7 8 9 10
S O R T E X A M P L E
1 0 O S R T E X A M P L E
2 1 O R S T E X A M P L E
3 3 O R S T E X A M P L E
4 0 E O R S T X A M P L E
5 5 E O R S T X A M P L E
6 0 A E O R S T X M P L E
7 2 A E M O R S T X P L E
8 4 A E M O P R S T X L E
9 2 A E L M O P R S T X E
10 2 A E E L M O P R S T X
A E E L M O P R S T X

3. Mergesort (top-down)
Given two sorted subarrays a[lo] to a[mid] and a[mid+1] to a[hi], replace with sorted subarray a[lo] to a[hi].

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
M E R G E S O R T E X A M P L E
merge(a, aux, 0, 0, 1) E M R G E S O R T E X A M P L E
merge(a, aux, 2, 2, 3) E M G R E S O R T E X A M P L E
merge(a, aux, 0, 1, 3) E G M R E S O R T E X A M P L E
merge(a, aux, 4, 4, 5) E G M R E S O R T E X A M P L E
merge(a, aux, 6, 6, 7) E G M R E S O R T E X A M P L E
merge(a, aux, 4, 5, 7) E G M R E O R S T E X A M P L E
merge(a, aux, 0, 3, 7) E E G M O R R S T E X A M P L E
merge(a, aux, 8, 8, 9) E E G M O R R S E T X A M P L E
merge(a, aux, 10, 10, 11) E E G M O R R S E T A X M P L E
merge(a, aux, 8, 9, 11) E E G M O R R S A E T X M P L E
merge(a, aux, 12, 12, 13) E E G M O R R S A E T X M P L E
merge(a, aux, 14, 14, 15) E E G M O R R S A E T X M P E L
merge(a, aux, 12, 13, 15) E E G M O R R S A E T X E L M P
merge(a, aux, 8, 11, 15) E E G M O R R S A E E L M P T X
merge(a, aux, 0, 7, 15) A E E E E G L M M O P R R S T X

4. Quicksort (standard, no shuffle)
Repeat until i and j pointers cross.
・Scan i from left to right so long as (a[i] < a[lo]).
・Scan j from right to left so long as (a[j] > a[lo]).
・Exchange a[i] with a[j].
When pointers cross.
・Exchange a[lo] with a[j].

lo j hi 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Q U I C K S O R T E X A M P L E - initial values
K R A T E L E P U I M Q C X O S - random shuffle
0 5 15 E C A I E K L P U T M Q R X O S
0 3 4 E C A E I K L P U T M Q R X O S
0 2 2 A C E E I K L P U T M Q R X O S
0 0 1 A C E E I K L P U T M Q R X O S
1 1 A C E E I K L P U T M Q R X O S
4 4 A C E E I K L P U T M Q R X O S
6 6 15 A C E E I K L P U T M Q R X O S
7 9 15 A C E E I K L M O P T Q R X U S
7 7 8 A C E E I K L M O P T Q R X U S
8 8 A C E E I K L M O P T Q R X U S
10 13 15 A C E E I K L M O P S Q R T U X
10 12 12 A C E E I K L M O P R Q S T U X
10 11 11 A C E E I K L M O P Q R S T U X
10 10 A C E E I K L M O P Q R S T U X
14 14 15 A C E E I K L M O P Q R S T U X
15 15 A C E E I K L M O P Q R S T U X
A C E E I K L M O P Q R S T U X

5. Heapsort
Basic plan for in-place sort.
・Create max-heap with all N keys.
Heap construction. Build max heap using bottom-up method.
・Repeatedly remove the maximum key.
Sortdown. Repeatedly delete the largest remaining item.

HTTP

HTTP (англ. HyperText Transfer Protocol — «протокол передачи гипертекста») — протокол прикладного уровня передачи данных (изначально — в виде гипертекстовых документов в формате HTML, в настоящий момент используется для передачи произвольных данных). Основой HTTP является технология «клиент-сервер», то есть предполагается существование потребителей (клиентов), которые инициируют соединение и посылают запрос, и поставщиков (серверов), которые ожидают соединения для получения запроса, производят необходимые действия и возвращают обратно сообщение с результатом.

Обмен сообщениями идёт по обыкновенной схеме «запрос-ответ».  Для идентификации ресурсов HTTP использует глобальные URI (Universal Resource Identifier). В отличие от многих других протоколов, HTTP не сохраняет своего состояния. Это означает отсутствие сохранения промежуточного состояния между парами «запрос-ответ». Компоненты, использующие HTTP, могут самостоятельно осуществлять сохранение информации о состоянии, связанной с последними запросами и ответами (например, «куки» на стороне клиента, «сессии» на стороне сервера). Браузер, посылающий запросы, может отслеживать задержки ответов. Сервер может хранить IP-адреса и заголовки запросов последних клиентов. Однако сам протокол не осведомлён о предыдущих запросах и ответах, в нём не предусмотрена внутренняя поддержка состояния, к нему не предъявляются такие требования.

Особенностью протокола HTTP является возможность указать в запросе и ответе способ представления одного и того же ресурса по различным параметрам: формату, кодировке, языку и т. д. (В частности для этого используется HTTP-заголовок.)

CSS transition trick