Skip to content

Commit 26bebf7

Browse files
authored
Merge pull request #6437 from duendeintemporal/main
#7 - javascript
2 parents 40a48aa + 02955eb commit 26bebf7

File tree

2 files changed

+664
-0
lines changed

2 files changed

+664
-0
lines changed
Lines changed: 291 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,291 @@
1+
/* #07 Pilas y Colas */
2+
//I use GPT to generate accurate comments and also as a reference.
3+
4+
//shorthand for console.log()
5+
let log = console.log.bind(console);
6+
7+
//The array structure can be useful in JavaScript to simulate stacks and queues.
8+
9+
/* A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means that the last element added to the stack is the first one to be removed. You can think of it like a stack of plates: you add plates to the top and also remove them from the top.
10+
Key Operations:
11+
12+
Push: Add an element to the top of the stack.
13+
Pop: Remove the element from the top of the stack.
14+
Peek/Top: Retrieve the top element without removing it.
15+
IsEmpty: Check if the stack is empty.
16+
*/
17+
18+
//Pila(Stack)
19+
let stack = [1,2,3,4];
20+
21+
//view the contents of a stack
22+
log('view stack: ', stack); // view stack: [ 1, 2, 3, 4 ]
23+
24+
//add an element to the stack
25+
stack.push(5);
26+
log('add an element: ', stack); // add an element: [ 1, 2, 3, 4, 5 ]
27+
28+
//get the size of the stack
29+
log('size: ', stack.length); // size: 5
30+
31+
//get the last value of the stack
32+
log('last value of the stack: ', stack[stack.length - 1]); // last value of the stack: 5
33+
34+
//remove the last value from the stack and print its value
35+
log('delete and return the last value: ', stack.pop()); // delete and return the last value: 5
36+
37+
//empty the stack
38+
stack = [];
39+
log('empty the stack: ', stack); // empty the stack: []
40+
41+
/* we can also enclosed in a function or a class for better organization and reusability */
42+
43+
class Stack {
44+
constructor(initialItems = []) {
45+
this.items = Array.isArray(initialItems) ? initialItems : [];
46+
}
47+
48+
push(element) {
49+
this.items.push(element);
50+
}
51+
52+
pop() {
53+
if (this.isEmpty()) {
54+
console.error("Stack is empty. Cannot pop an element.");
55+
return null;
56+
}
57+
return this.items.pop();
58+
}
59+
60+
peek() {
61+
if (this.isEmpty()) {
62+
console.error("Stack is empty. Cannot peek.");
63+
return null;
64+
}
65+
return this.items[this.items.length - 1];
66+
}
67+
68+
empty() {
69+
return this.items = [];
70+
}
71+
72+
isEmpty() {
73+
return this.items.length === 0;
74+
}
75+
76+
size() {
77+
return this.items.length;
78+
}
79+
}
80+
81+
const stack2 = new Stack([55, 76, 98, 100]);
82+
log('Initial stack2:', stack2.items); // [55, 76, 98, 100]
83+
84+
stack2.push(32);
85+
log('After pushing 32:', stack2.items); // [55, 76, 98, 100, 32]
86+
87+
log('Peek:', stack2.peek()); // 32
88+
89+
log('Pop:', stack2.pop()); // 32
90+
log('After popping:', stack2.items); // [55, 76, 98, 100]
91+
92+
log('Pop all elements:');
93+
while (!stack2.isEmpty()) {
94+
log('Popped:', stack2.pop());
95+
} // or we can just empty the stack stack2.empty()
96+
97+
log('Final stack2:', stack2.items); // []
98+
log('Pop from empty stack2:', stack2.pop()); // Stack is empty. Cannot pop an element. & null
99+
100+
101+
//Cola(Queue)
102+
103+
/* A queue is a linear data structure that follows the First In, First Out (FIFO) principle. This means that the first element added to the queue is the first one to be removed. You can think of it like a line of people waiting for service: the first person in line is the first to be served.
104+
Key Operations:
105+
106+
Enqueue: Add an element to the end of the queue.
107+
Dequeue: Remove the element from the front of the queue.
108+
Front/Peek: Retrieve the front element without removing it.
109+
IsEmpty: Check if the queue is empty.
110+
*/
111+
112+
let queue = [8,5,4,2,1];
113+
114+
//view the contents of a queue
115+
log('view queue: ', queue); // view queue: [ 8, 5, 4, 2, 1 ]
116+
117+
//add elements to the queue
118+
queue.push(7);
119+
log('add an element: ', queue); // add an element: [ 8, 5, 4, 2, 1, 7 ]
120+
121+
//get the size of the queue
122+
log('size: ', queue.length); // size: 6
123+
124+
//get the first value of the queue
125+
log('first value: ', queue[0]); // first value: 8
126+
127+
//remove the first value from the queue and print its value
128+
log('delete and return the first value ', queue.shift()); // delete and return the first value 8
129+
130+
//empty the queue
131+
queue = [];
132+
log('empty the queue: ', queue); // empty the queue: []
133+
134+
/* we can also enclosed in a function or a class for better organization and reusability */
135+
136+
class Queue {
137+
constructor(initialItems = []) {
138+
this.items = Array.isArray(initialItems) ? initialItems : [];
139+
}
140+
141+
enqueue(element) {
142+
this.items.push(element);
143+
}
144+
145+
dequeue() {
146+
if (this.isEmpty()) {
147+
console.error("Queue is empty. Cannot dequeue an element.");
148+
return null;
149+
}
150+
return this.items.shift();
151+
}
152+
153+
peek() {
154+
if (this.isEmpty()) {
155+
console.error("Queue is empty. Cannot peek.");
156+
return null;
157+
}
158+
return this.items[0];
159+
}
160+
empty() {
161+
return this.items = [];
162+
}
163+
164+
isEmpty() {
165+
return this.items.length === 0;
166+
}
167+
168+
size() {
169+
return this.items.length;
170+
}
171+
}
172+
173+
const queue2 = new Queue([45, 32, 16]);
174+
log('Initial queue2:', queue2.items); // [45, 32, 16]
175+
176+
queue2.enqueue(77);
177+
log('After enqueueing 4:', queue2.items); // [45, 32, 16, 77]
178+
179+
log('Peek:', queue2.peek()); // 45
180+
181+
log('Dequeue:', queue2.dequeue()); // 45
182+
log('After dequeueing:', queue2.items); // [32, 16, 77]
183+
184+
log('Dequeue all elements:');
185+
while (!queue2.isEmpty()) {
186+
log('Dequeued:', queue2.dequeue());
187+
} // or we can just empty the queue queue2.empty()
188+
189+
log('Final queue2:', queue2.items); // []
190+
log('Dequeue from empty queue2:', queue2.dequeue()); // Queue is empty. Cannot dequeue an element. & null
191+
192+
193+
//Additional exercises:
194+
/* #1 Simulate the behavior of the back and forward buttons in a browser. */
195+
196+
let documentsQueue = [
197+
{ name: 'Tratado de Tantra.txt', content: 'Here comes the content of Tratado de Tantra.' },
198+
{ name: 'Nada Sagrado.doc', content: 'Here comes the content of Nada Sagrado.' },
199+
{ name: 'El Blanco Invisible.pdf', content: 'Here comes the content of El Blanco Invisible.' }
200+
];
201+
202+
function printQueue(arr){
203+
if(arr.length == 0){
204+
log('There no element to print in the queue!')
205+
return;
206+
}
207+
while (arr.length > 0) {
208+
const document = arr.shift(); // Get the first document
209+
log('Printing document:', document.name);
210+
log('Content:', document.content);
211+
}
212+
log('There no more element to print in the queue!')
213+
}
214+
215+
printQueue(documentsQueue);/* Printing document: Tratado de Tantra.txt
216+
Content: Here comes the content of Tratado de Tantra.
217+
Printing document: Nada Sagrado.doc
218+
Content: Here comes the content of Nada Sagrado.
219+
Printing document: El Blanco Invisible.pdf
220+
Content: Here comes the content of El Blanco Invisible.
221+
There no more element to print in the queue! */
222+
223+
/* To read and print the contents of documents in JavaScript, you would typically need to use a file reading mechanism. However, JavaScript running in a browser environment does not have direct access to the file system for security reasons. Instead, you can simulate reading the contents of the documents by using predefined content or by using the File API if you're working with file inputs. */
224+
225+
let urlStack = [];
226+
let currentIndex = -1; // To keep track of the current position.
227+
228+
function browseWeb(str = prompt('Enter a URL or the word "forward" or "back" to navigate in the browsing history.')) {
229+
const back = () => {
230+
if (currentIndex > 0) {
231+
currentIndex--;
232+
const previousUrl = urlStack[currentIndex];
233+
log('Location: ', previousUrl);
234+
// window.location = previousUrl; // Navigate to the previous URL.
235+
} else {
236+
log("There are no more pages back..");
237+
}
238+
};
239+
240+
const forward = () => {
241+
if (currentIndex < urlStack.length - 1) {
242+
currentIndex++;
243+
const nextUrl = urlStack[currentIndex];
244+
log('Location: ', nextUrl);
245+
// window.location = nextUrl; // Navigate to the next URL.
246+
} else {
247+
log("There are no more pages forward.");
248+
}
249+
};
250+
251+
if (str !== 'back' && str !== 'forward') {
252+
if (currentIndex < urlStack.length - 1) {
253+
urlStack = urlStack.slice(0, currentIndex + 1); // Clear forward if navigation has occurred.
254+
} // the standard behavior of a web browser's navigation history,
255+
urlStack.push(str);
256+
currentIndex++;
257+
// window.location = str; // Navigate to the new URL.
258+
log('Location: ', str);
259+
} else if (str === 'back') {
260+
back();
261+
} else if (str === 'forward') {
262+
forward();
263+
}
264+
}
265+
266+
267+
browseWeb('www.lectura_prospectiva.net'); // Location: www.lectura_prospectiva.net
268+
browseWeb('www.test.web'); // Location: www.test.web
269+
browseWeb('back'); // www.lectura_prospectiva.net
270+
browseWeb('forward'); // www.test.web
271+
272+
273+
window.addEventListener('load', ()=>{
274+
const body = document.querySelector('body');
275+
const title = document.createElement('h1');
276+
277+
body.style.setProperty('background', '#000');
278+
body.style.setProperty('text-align', 'center');
279+
280+
title.textContent = 'Retosparaprogramadores #7.';
281+
title.style.setProperty('font-size', '3.5vmax');
282+
title.style.setProperty('color', '#fff');
283+
title.style.setProperty('line-height', '100vh');
284+
285+
body.appendChild(title);
286+
287+
setTimeout(()=>{
288+
alert('Retosparaprogramadores #7. Please open the Browser Developer Tools.');
289+
}, 2000);
290+
log( 'Retosparaprogramadores #7');
291+
});

0 commit comments

Comments
 (0)