Skip to content

Commit ae1458e

Browse files
committed
Add functional implementation
1 parent 2c7148c commit ae1458e

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

JavaScript/3-function.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
'use strict';
2+
3+
const renderers = {
4+
abstract: () => console.log('Not implemented'),
5+
console: data => {
6+
console.table(data);
7+
},
8+
web: data => {
9+
const keys = Object.keys(data[0]);
10+
const line = row => '<tr>' +
11+
keys.map(key => `<td>${row[key]}</td>`).join('') +
12+
'</tr>';
13+
const output = [
14+
'<table><tr>',
15+
keys.map(key => `<th>${key}</th>`).join(''),
16+
'</tr>',
17+
data.map(line).join(''),
18+
'</table>',
19+
];
20+
console.log(output.join(''));
21+
},
22+
markdown: data => {
23+
const keys = Object.keys(data[0]);
24+
const line = row => '|' +
25+
keys.map(key => `${row[key]}`).join('|') + '|\n';
26+
const output = [
27+
'|', keys.map(key => `${key}`).join('|'), '|\n',
28+
'|', keys.map(() => '---').join('|'), '|\n',
29+
data.map(line).join(''),
30+
];
31+
console.log(output.join(''));
32+
},
33+
};
34+
35+
const context = rendererName => data => {
36+
const renderer = renderers[rendererName] || renderers.abstract;
37+
return renderer(data);
38+
};
39+
40+
// Usage
41+
42+
const non = context('unknown');
43+
const con = context('console');
44+
const web = context('web');
45+
const mkd = context('markdown');
46+
47+
const persons = [
48+
{ name: 'Marcus Aurelius', city: 'Rome', born: 121 },
49+
{ name: 'Victor Glushkov', city: 'Rostov on Don', born: 1923 },
50+
{ name: 'Ibn Arabi', city: 'Murcia', born: 1165 },
51+
{ name: 'Mao Zedong', city: 'Shaoshan', born: 1893 },
52+
{ name: 'Rene Descartes', city: 'La Haye en Touraine', born: 1596 },
53+
];
54+
55+
console.group('Abstract Strategy:');
56+
non(persons);
57+
console.groupEnd();
58+
59+
console.group('\nConsoleRenderer:');
60+
con(persons);
61+
console.groupEnd();
62+
63+
console.group('\nWebRenderer:');
64+
web(persons);
65+
console.groupEnd();
66+
67+
console.group('\nMarkdownRenderer');
68+
mkd(persons);
69+
console.groupEnd();

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