Skip to content

Commit abdbbe1

Browse files
committed
Fix code style
1 parent 292e465 commit abdbbe1

File tree

6 files changed

+293
-2
lines changed

6 files changed

+293
-2
lines changed

JavaScript/9-timer-iterable.js

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
'use strict';
22

3+
const { setTimeout } = require('node:timers/promises');
4+
35
class Timer {
46
#counter = 0;
57
#resolve = null;
@@ -29,8 +31,33 @@ class Timer {
2931

3032
const main = async () => {
3133
const timer = new Timer(1000);
32-
for await (const step of timer) {
33-
console.log({ step });
34+
35+
{
36+
console.log('start 1');
37+
for await (const step of timer) {
38+
console.log({ for: 1, step });
39+
}
40+
}
41+
42+
{
43+
console.log('start 2');
44+
const iter = timer[Symbol.asyncIterator]();
45+
do {
46+
console.log({ for: 2, iter });
47+
const { value, done } = await iter.next();
48+
console.log({ for: 2, step: value });
49+
} while (true);
50+
}
51+
52+
{
53+
console.log('start 3');
54+
const iter = timer[Symbol.asyncIterator]();
55+
do {
56+
console.log({ for: 3, iter });
57+
const { value, done } = await iter.next();
58+
const a = await iter.next();
59+
console.log({ for: 3, step: value });
60+
} while (true);
3461
}
3562
};
3663

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'use strict';
2+
3+
const API_EXCHANGE = {
4+
host: 'openexchangerates.org',
5+
path: 'api/latest.json?app_id=',
6+
key: '1f43ea96b1e343fe94333dd2b97a109d',
7+
};
8+
9+
const DEFAULT_RETRY = 3;
10+
11+
const getRate = async (currency, retry = DEFAULT_RETRY) => {
12+
console.log({ currency, retry });
13+
const { host, path, key } = API_EXCHANGE;
14+
const url = `https://${host}/${path}${key}`;
15+
const res = await fetch(url).catch(() => ({ ok: false }));
16+
if (!res.ok) {
17+
const attemptsLeft = retry - 1;
18+
if (attemptsLeft > 0) return getRate(currency, retry - 1);
19+
throw new Error('Can not get data');
20+
}
21+
const data = await res.json();
22+
const rate = data.rates[currency];
23+
return rate;
24+
};
25+
26+
const main = async () => {
27+
try {
28+
const rate = await getRate('UAH');
29+
console.log({ rate });
30+
} catch (err) {
31+
console.error({ err });
32+
}
33+
};
34+
35+
main();
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
'use strict';
2+
3+
const API_EXCHANGE = {
4+
host: 'openexchangerates.org',
5+
path: 'api/latest.json?app_id=',
6+
key: '1f43ea96b1e343fe94333dd2b97a109d',
7+
};
8+
9+
const DEFAULT_RETRY = 3;
10+
11+
const httpGet = async ({ url, retry = DEFAULT_RETRY }) => {
12+
console.log({ url, retry });
13+
const res = await fetch(url).catch(() => ({ ok: false }));
14+
if (!res.ok) {
15+
const attemptsLeft = retry - 1;
16+
if (attemptsLeft > 0) return httpGet({ url, retry: attemptsLeft });
17+
throw new Error('Can not get data');
18+
}
19+
return res.json();
20+
};
21+
22+
const getRate = async (currency) => {
23+
console.log({ currency });
24+
const { host, path, key } = API_EXCHANGE;
25+
const url = `https://${host}/${path}${key}`;
26+
const data = await httpGet({ url });
27+
const rate = data.rates[currency];
28+
return rate;
29+
};
30+
31+
const main = async () => {
32+
try {
33+
const rate = await getRate('UAH');
34+
console.log({ rate });
35+
} catch (err) {
36+
console.error({ err });
37+
}
38+
};
39+
40+
main();
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
'use strict';
2+
3+
const MOCK_DATASET = [
4+
{ name: 'Rome', population: 2761632, country: 10, type: 1 },
5+
{ name: 'Milan', population: 1371498, country: 10, type: 1 },
6+
{ name: 'Naples', population: 914758, country: 10, type: 1 },
7+
{ name: 'Turin', population: 848885, country: 10, type: 1 },
8+
{ name: 'Palermo', population: 630828, country: 10, type: 1 },
9+
{ name: 'Genoa', population: 560688, country: 10, type: 1 },
10+
{ name: 'Bologna', population: 392203, country: 10, type: 1 },
11+
{ name: 'Florence', population: 367150, country: 10, type: 1 },
12+
{ name: 'Bari', population: 316140, country: 10, type: 1 },
13+
{ name: 'Catania', population: 298324, country: 10, type: 1 },
14+
];
15+
16+
const MOCK_TIMEOUT = 1000;
17+
18+
class Query {
19+
constructor(table) {
20+
this.options = { table, fields: ['*'], where: {} };
21+
}
22+
23+
where(conditions) {
24+
Object.assign(this.options.where, conditions);
25+
return this;
26+
}
27+
28+
order(field) {
29+
this.options.order = field;
30+
return this;
31+
}
32+
33+
limit(count) {
34+
this.options.limit = count;
35+
return this;
36+
}
37+
38+
then(resolve) {
39+
const { table, fields, where, limit, order } = this.options;
40+
const cond = Object.entries(where).map((e) => e.join('=')).join(' AND ');
41+
const sql = `SELECT ${fields} FROM ${table} WHERE ${cond}`;
42+
const opt = `ORDER BY ${order} LIMIT ${limit}`;
43+
const query = sql + ' ' + opt;
44+
setTimeout(() => {
45+
resolve({ query, dataset: MOCK_DATASET });
46+
}, MOCK_TIMEOUT);
47+
}
48+
}
49+
50+
// Usage
51+
52+
(async () => {
53+
54+
const cities = await new Query('cities')
55+
.where({ country: 10, type: 1 })
56+
.order('population')
57+
.limit(10)
58+
.then((result) => {
59+
const projection = new Map();
60+
for (const record of result.dataset) {
61+
const { name, population } = record;
62+
projection.set(name, population);
63+
}
64+
return projection;
65+
});
66+
67+
console.log(cities);
68+
69+
})();
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
'use strict';
2+
3+
const MOCK_DATASET = [
4+
{ name: 'Rome', population: 2761632, country: 10, type: 1 },
5+
{ name: 'Milan', population: 1371498, country: 10, type: 1 },
6+
{ name: 'Naples', population: 914758, country: 10, type: 1 },
7+
{ name: 'Turin', population: 848885, country: 10, type: 1 },
8+
{ name: 'Palermo', population: 630828, country: 10, type: 1 },
9+
{ name: 'Genoa', population: 560688, country: 10, type: 1 },
10+
{ name: 'Bologna', population: 392203, country: 10, type: 1 },
11+
{ name: 'Florence', population: 367150, country: 10, type: 1 },
12+
{ name: 'Bari', population: 316140, country: 10, type: 1 },
13+
{ name: 'Catania', population: 298324, country: 10, type: 1 },
14+
];
15+
16+
const MOCK_TIMEOUT = 1000;
17+
18+
class Query {
19+
constructor(table) {
20+
this.options = { table, fields: ['*'], where: {} };
21+
}
22+
23+
where(conditions) {
24+
Object.assign(this.options.where, conditions);
25+
return this;
26+
}
27+
28+
order(field) {
29+
this.options.order = field;
30+
return this;
31+
}
32+
33+
limit(count) {
34+
this.options.limit = count;
35+
return this;
36+
}
37+
38+
then(resolve) {
39+
const { table, fields, where, limit, order } = this.options;
40+
const cond = Object.entries(where).map((e) => e.join('=')).join(' AND ');
41+
const sql = `SELECT ${fields} FROM ${table} WHERE ${cond}`;
42+
const opt = `ORDER BY ${order} LIMIT ${limit}`;
43+
const query = sql + ' ' + opt;
44+
return new Promise((fulfill) => {
45+
setTimeout(() => {
46+
const result = { query, dataset: MOCK_DATASET };
47+
fulfill(resolve(result));
48+
}, MOCK_TIMEOUT);
49+
});
50+
}
51+
}
52+
53+
// Usage
54+
55+
(async () => {
56+
57+
const cities = await new Query('cities')
58+
.where({ country: 10, type: 1 })
59+
.order('population')
60+
.limit(10)
61+
.then((result) => {
62+
const projection = new Map();
63+
for (const record of result.dataset) {
64+
const { name, population } = record;
65+
projection.set(name, population);
66+
}
67+
return projection;
68+
});
69+
70+
console.log(cities);
71+
72+
})();
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
'use strict';
2+
3+
const fs = require('node:fs');
4+
const stream = require('node:stream');
5+
const { Console } = require('node:console');
6+
const PATH = process.cwd();
7+
8+
const shortenPath = new stream.Transform({
9+
transform(chunk, encoding, callback) {
10+
const line = String(chunk)
11+
.replaceAll(PATH, '')
12+
.replaceAll('\n', ' ')
13+
.replaceAll(' ', ' ')
14+
.trim();
15+
callback(null, line);
16+
},
17+
});
18+
19+
const TIME_START = 11;
20+
const TIME_END = 19;
21+
22+
const getTimestamp = () => {
23+
const time = new Date().toISOString();
24+
return time.substring(TIME_START, TIME_END);
25+
};
26+
27+
const addTimestamp = new stream.Transform({
28+
transform(chunk, encoding, callback) {
29+
const line = getTimestamp() + ' ' + String(chunk);
30+
callback(null, line);
31+
},
32+
});
33+
34+
const [date] = new Date().toISOString().split('T');
35+
const log = fs.createWriteStream(`./${date}.log`);
36+
const stdout = stream.compose(addTimestamp, log);
37+
const stderr = stream.compose(shortenPath, stdout);
38+
39+
const console = new Console({ stdout, stderr });
40+
41+
try {
42+
console.log('Logging examle');
43+
console.table(Object.entries(log));
44+
const data = {};
45+
data.collUnknownMethod();
46+
} catch (error) {
47+
console.error(error);
48+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy