Skip to content

Commit

Permalink
feat(jsnad): lab solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
jebarsoba committed Dec 1, 2022
1 parent b18a9a1 commit e7a394d
Show file tree
Hide file tree
Showing 59 changed files with 20,358 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Here's the directory structure and how to run each project:
- __/others__
- /__eloquent-javascript__: my solutions for the [Eloquent JavaScript](https://eloquentjavascript.net/) book exercises (run with node <file.js>)
- /__javascript-interview-questions__: npm t
- /__jsnad__: my solutions for the [LFW211: Node.js Application Development (Linux Foundation)](https://training.linuxfoundation.org/training/) lab exercises
- /__msgpack-lite-sandbox__: playing with msgpack (node index.js)
- /__openui5__: tutorials from the [OpenUI5](https://openui5.hana.ondemand.com/#/topic) documentation website (check the wiki md file on each project folder)
- /__qlikview-examples__: [Getting Started with QlikView Series](https://community.qlik.com/docs/DOC-1986#getStart) tutorials
Expand All @@ -18,4 +19,4 @@ Here's the directory structure and how to run each project:
- __Introduction to Data Structures & Algorithms in Java__, /ds-and-a
- /csharp-solutions: ./DSAndA.Test/dotnet test
- /javascript-solutions: npm t
- /typescript-solutions: npm t
- /typescript-solutions: npm t
4 changes: 4 additions & 0 deletions others/jsnad/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
.nyc_output/
project/
out.txt
19 changes: 19 additions & 0 deletions others/jsnad/ch-10/labs-1/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"use strict";
const assert = require("assert");

function parseUrl(str) {
let parsed = null;
try {
parsed = new URL(str);
} catch (err) {
return null;
}
return parsed;
}

assert.doesNotThrow(() => {
parseUrl("invalid-url");
});
assert.equal(parseUrl("invalid-url"), null);
assert.deepEqual(parseUrl("http://example.com"), new URL("http://example.com"));
console.log("passed!");
24 changes: 24 additions & 0 deletions others/jsnad/ch-10/labs-2/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"use strict";
const fs = require("fs");
const assert = require("assert");

async function read(file) {
let content = null;
try {
content = await fs.promises.readFile(file);
} catch (error) {
throw new Error("failed to read");
}
return content;
}

async function check() {
await assert.rejects(
read("not-a-valid-filepath"),
new Error("failed to read")
);
assert.deepEqual(await read(__filename), fs.readFileSync(__filename));
console.log("passed!");
}

check();
7 changes: 7 additions & 0 deletions others/jsnad/ch-11/labs-1/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"use strict";
const assert = require("assert");
const buffer = Buffer.alloc(4096);
console.log(buffer);

for (const byte of buffer) assert.equal(byte, 0);
console.log("passed!");
16 changes: 16 additions & 0 deletions others/jsnad/ch-11/labs-2/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"use strict";
const assert = require("assert");
const str = "buffers are neat";
const base64 = Buffer.from(Buffer.from(str).toString("base64")); // convert str to base64

console.log(base64);

assert.equal(
base64,
Buffer.from([
89, 110, 86, 109, 90, 109, 86, 121, 99, 121, 66, 104, 99, 109, 85, 103, 98,
109, 86, 104, 100, 65, 61, 61,
])
);

console.log("passed!");
30 changes: 30 additions & 0 deletions others/jsnad/ch-12/labs-1/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"use strict";
const { Readable, Writable } = require("stream");
const assert = require("assert");
const createWritable = () => {
const sink = [];
let piped = false;
setImmediate(() => {
assert.strictEqual(piped, true, "use the pipe method");
assert.deepStrictEqual(sink, ["a", "b", "c"]);
});
const writable = new Writable({
decodeStrings: false,
write(chunk, enc, cb) {
sink.push(chunk);
cb();
},
final() {
console.log("passed!");
},
});
writable.once("pipe", () => {
piped = true;
});
return writable;
};
const readable = Readable.from(["a", "b", "c"]);
const writable = createWritable();
readable.pipe(writable);

// TODO - send all data from readable to writable:
37 changes: 37 additions & 0 deletions others/jsnad/ch-12/labs-2/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"use strict";
const {
Readable,
Writable,
Transform,
PassThrough,
pipeline,
} = require("stream");
const assert = require("assert");
const createWritable = () => {
const sink = [];
const writable = new Writable({
write(chunk, enc, cb) {
sink.push(chunk.toString());
cb();
},
});
writable.sink = sink;
return writable;
};
const readable = Readable.from(["a", "b", "c"]);
const writable = createWritable();

// TODO: replace the pass through stream
// with a transform stream that uppercases
// incoming characters
const transform = new Transform({
transform(chunk, enc, next) {
next(null, chunk.toString().toUpperCase());
},
});

pipeline(readable, transform, writable, (err) => {
assert.ifError(err);
assert.deepStrictEqual(writable.sink, ["A", "B", "C"]);
console.log("passed!");
});
33 changes: 33 additions & 0 deletions others/jsnad/ch-13/labs-1/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"use strict";
const assert = require("assert");
const { join, basename } = require("path");
const fs = require("fs");
const project = join(__dirname, "project");
try {
fs.rmdirSync(project, { recursive: true });
} catch (err) {}
const files = Array.from(Array(5), () => {
return join(project, Math.random().toString(36).slice(2));
});
files.sort();
fs.mkdirSync(project);
for (const f of files) fs.closeSync(fs.openSync(f, "w"));

const out = join(__dirname, "out.txt");

function exercise() {
// TODO read the files in the project folder
// and write the to the out.txt file
fs.writeFileSync(out, files.map((filename) => basename(filename)).join(","));
}

exercise();
assert.deepStrictEqual(
fs
.readFileSync(out)
.toString()
.split(",")
.map((s) => s.trim()),
files.map((f) => basename(f))
);
console.log("passed!");
57 changes: 57 additions & 0 deletions others/jsnad/ch-13/labs-2/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"use strict";
const assert = require("assert");
const { join } = require("path");
const fs = require("fs");
const { promisify } = require("util");
const timeout = promisify(setTimeout);
const project = join(__dirname, "project");
try {
fs.rmdirSync(project, { recursive: true });
} catch (err) {
console.error(err);
}
fs.mkdirSync(project);

let answer = "";

async function writer() {
const { open, chmod, mkdir } = fs.promises;
const pre = join(project, Math.random().toString(36).slice(2));
const handle = await open(pre, "w");
await handle.close();
await timeout(500);
exercise(project);
const file = join(project, Math.random().toString(36).slice(2));
const dir = join(project, Math.random().toString(36).slice(2));
const add = await open(file, "w");
await add.close();
await mkdir(dir);
await chmod(pre, 0o444);
await timeout(500);
assert.strictEqual(
answer,
file,
"answer should be the file (not folder) which was added"
);
console.log("passed!");
process.exit();
}

writer().catch((err) => {
console.error(err);
process.exit(1);
});

function exercise(project) {
const files = new Set(fs.readdirSync(project));
fs.watch(project, (evt, filename) => {
try {
const filepath = join(project, filename);
const stat = fs.statSync(filepath);

// TODO - only set the answer variable if the filepath
// is both newly created AND does not point to a directory
if (!files.has(filename) && !stat.isDirectory()) answer = filepath;
} catch (err) {}
});
}
3 changes: 3 additions & 0 deletions others/jsnad/ch-14/labs-1/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const os = require("os");
console.log(os.platform());
process.exit(1);
12 changes: 12 additions & 0 deletions others/jsnad/ch-14/labs-1/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
"use strict";
const { spawnSync } = require("child_process");
const assert = require("assert");
const { status, stdout } = spawnSync(process.argv[0], [__dirname]);

assert.notStrictEqual(status, 0, "must exit with a non-zero code");
assert.match(
stdout.toString(),
/^(d|w|l|aix|.+bsd|sunos|gnu)/i,
"must output OS identifier"
);
console.log("passed!");
9 changes: 9 additions & 0 deletions others/jsnad/ch-14/labs-2/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
"use strict";
const os = require("os");

setTimeout(() => {
console.log(process.uptime()); // TODO output uptime of process
console.log(os.uptime()); // TODO output uptime of OS
console.log(os.totalmem()); // TODO output total system memory
console.log(process.memoryUsage().heapTotal); // TODO output total heap memory
}, 1000);
40 changes: 40 additions & 0 deletions others/jsnad/ch-14/labs-2/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"use strict";
const assert = require("assert");
const os = require("os");
const { runInThisContext } = require("vm");
const run = (s) => runInThisContext(Buffer.from(s, "base64"));
const { log } = console;
const queue = [
(line) =>
assert.strictEqual(
Math.floor(line),
1,
"first log line should be the uptime of the process"
),
(line) =>
assert.strictEqual(
line,
run("KG9zKSA9PiBvcy51cHRpbWUoKQ==")(os),
"second log line should be the uptime of the OS"
),
(line) =>
assert.strictEqual(
line,
run("KG9zKSA9PiBvcy50b3RhbG1lbSgp")(os),
"third line should be total system memory"
),
(line) =>
assert.strictEqual(
line,
run("cHJvY2Vzcy5tZW1vcnlVc2FnZSgpLmhlYXBUb3RhbA=="),
"fourth line should be total process memory"
),
];
console.log = (line) => {
queue.shift()(line);
if (queue.length === 0) {
console.log = log;
console.log("passed!");
}
};
require(".");
15 changes: 15 additions & 0 deletions others/jsnad/ch-15/labs-1/child.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"use strict";
const assert = require("assert");
const clean = (env) =>
Object.fromEntries(
Object.entries(env).filter(([k]) => !/^(_.*|pwd|shlvl)/i.test(k))
);
const env = clean(process.env);

assert.strictEqual(env.MY_ENV_VAR, "is set");
assert.strictEqual(
Object.keys(env).length,
1,
"child process should have only one env var"
);
console.log("passed!");
15 changes: 15 additions & 0 deletions others/jsnad/ch-15/labs-1/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"use strict";

function exercise(myEnvVar) {
// TODO return a child process with
// a single environment variable set
// named MY_ENV_VAR. The MY_ENV_VAR
// environment variable's value should
// be the value of the myEnvVar parameter
// passed to this exercise function
return require("child_process").spawn(process.execPath, ["child.js"], {
env: { MY_ENV_VAR: myEnvVar },
});
}

module.exports = exercise;
Loading

0 comments on commit e7a394d

Please sign in to comment.