-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
109 lines (97 loc) · 2.51 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// create the image data
const imageWidth = 20;
const imageHeight = 8;
const imageData = createImageData();
// draw head
drawRectangle(0, 0, 20, 8);
// eyes
drawDot(7, 2);
drawDot(12, 2);
// smile
drawDot(4, 4);
drawHorizontalLine(4, 5, 12);
drawDot(15, 4);
// output what we drew to the console
outputImage();
function drawRectangle(
x: number,
y: number,
width: number,
height: number
) {
// top
drawHorizontalLine(x, y, width);
// bottom
drawHorizontalLine(x, y + height - 1, width);
// left
drawVerticalLine(x, y, height);
// right
drawVerticalLine(x + width - 1, y, height);
}
function drawDot(x: number, y: number) {
if (isPointInImage(x,y)) {
imageData[y * imageWidth + x] = true;
}
}
function drawHorizontalLine(x:number, y:number, length:number) {
for (let i=0 ; i < length; i++) {
drawDot(x + i, y);
}
}
function drawVerticalLine(x:number, y:number, length:number) {
for (let i = 0; i < length; i++) {
drawDot(x, y + i)
}
}
/**
* Gets if the provided point is in the image.
* @param x - The horizontal position within
* the image.
* @param y - The vertical position within
* the image.
*/
function isPointInImage(x: number, y: number) {
return x >= 0 && x < imageWidth && y >= 0 && y < imageHeight;
}
/**
* Outputs the image data state to the console.
* @param onChar - Character to render an
* "on" pixel with.
* @param offChar - Character to render an
* "off" pixel with.
*/
function outputImage(onChar = "X", offChar = " ") {
let text = "";
for (let i = 0; i < imageData.length; i++) {
if (i > 0 && i % imageWidth === 0) {
text += "\n"; // new line
}
text += imageData[i] ? onChar : offChar;
}
console.log(text);
}
/**
* Creates an array of booleans where a pixel
* is "on" when the value is `true` and "off"
* when the value is `false`.
*
* The pixel values are stored in rows
* (row-major order) where the index of a
* pixel in the array can be found via:
*
* index = y * imageWidth + x
*
* `x` is the horizontal position in the image
* and `y` is the vertical position from the top
* left corner.
*
* Note: This function has a return type annotation
* of `boolean[]`. That means it's an array of
* booleans. We'll learn more about this in a
* future module.
*/
function createImageData(): boolean[] {
// create array of size `length` containing `false` values
const length = imageWidth * imageHeight;
return new Array(length).fill(false);
}