Skip to content

Instantly share code, notes, and snippets.

@rodmatola
Last active December 6, 2023 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodmatola/f5a81dd11961cb383f3750edc5a77813 to your computer and use it in GitHub Desktop.
Save rodmatola/f5a81dd11961cb383f3750edc5a77813 to your computer and use it in GitHub Desktop.
Dev.Pro
/*
Task 2: Inventory Management
Context: You are developing a simple inventory management system for a small store.
You need to create a function that takes a list of products with their names, prices, and stock levels, and returns a sorted list of products based on a given sort key (name, price, or stock) and order (ascending or descending).
Example Input:
products = [
{""name"": ""Product A"", ""price"": 100, ""stock"": 5},
{""name"": ""Product B"", ""price"": 200, ""stock"": 3},
{""name"": ""Product C"", ""price"": 50, ""stock"": 10}
]
sort_key = ""price""
ascending = False
Expected Output: [
{""name"": ""Product B"", ""price"": 200, ""stock"": 3},
{""name"": ""Product A"", ""price"": 100, ""stock"": 5},
{""name"": ""Product C"", ""price"": 50, ""stock"": 10}
]
*/
const inventory = (products, sort_key, ascending) => {
if (ascending && sort_key != "name") {
products.sort((a, b) => {
return a[sort_key] - b[sort_key];
});
} else {
products.sort((a, b) => {
return b[sort_key] - a[sort_key];
});
}
if (sort_key == "name") {
products.sort((a, b) => {
let fa = a["name"].toLowerCase();
let fb = b["name"].toLowerCase();
if (ascending) {
if (fa < fb) {
return -1;
}
} else {
if (fa > fb) {
return -1;
}
}
});
}
return products
}
module.exports = inventory;
/*
Task 1: Logger
Context: Your team is working on a project where you need to log various events and errors. You are asked to create a simple logging function that writes messages to a text file with a timestamp.
Example usage:
log_message("application.log", "User logged in", "INFO")
log_message("application.log", "Failed login attempt", "WARNING")
Expected Output in application.log:
[2023-04-24 12:34:56] [INFO] User logged in
[2023-04-24 12:35:10] [WARNING] Failed login attempt
RESOLUTION COMMENTS
Since was asked a simple logging funcion, I choose not to use other console methos, like console.warn() and console.error(), or severity levels specified by RFC5424.
*/
const log_message = (app, message, level) => {
const fs = require('node:fs');
const dateTime = new Date();
const year = dateTime.getFullYear();
const month = ("0" + (dateTime.getMonth() + 1)).slice(-2);
const day = ("0" + dateTime.getDate()).slice(-2);
const hours = dateTime.getHours();
const minutes = dateTime.getMinutes();
const seconds = dateTime.getSeconds();
const logMessage = (`[${year}-${month}-${day} ${hours}:${minutes}:${seconds}] [${level}] ${message}\n`);
try {
fs.appendFileSync(app, logMessage);
} catch (err) {
console.error(err);
}
return logMessage;
}
module.exports = log_message;
/*
Task 1.1: Tests
Write tests scenarios for Logger
RESOLUTION COMMENTS
ATTENTION: This file MUST BE in same folder of log_message.js in order to work without any further configuration.
I decided to not use any external package for the tasks, that's why I use Math.random() as filenames and messages.
*/
const { describe, test, beforeEach } = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
const { exec } = require("node:child_process");
const log_message = require('./log_message');
const levels = [
'ERROR',
'WARN',
'INFO',
'DEBUG'
];
let fileName;
describe('logger tests', async () => {
beforeEach(() => {
exec('rm *.log');
fileName = `${Math.random()}.log`;
});
test("file should exists", () => {
log_message(fileName, "User logged in", "INFO");
const isFile = fs.existsSync(fileName);
assert.ok(isFile);
});
test("log message should have the correct format", () => {
const level = levels[
Math.floor(Math.random() * levels.length)
];
const message = Math.random().toString();
const logMessage = log_message(fileName, message, level);
const messageElements = logMessage.split(" ");
const date = messageElements[0];
const dateRegex = /^\[20\d{2}-(0[1-9]|1[1,2])-(0[1-9]|[12][0-9]|3[01])/;
const time = messageElements[1];
const timeRegex = /^(0?[0-9]|1[0-9]|2[0-3]):(0?[1-5]?[0-9]):(0?[1-5]?[0-9])\]$/;
const lvl = messageElements[2];
const lvlRegex = /^\[[A-Z]*\]$/;
const msg = messageElements[3];
const msgRegex = /[a-zA-Z0-9]/;
assert.match(date, dateRegex);
assert.match(time, timeRegex);
assert.match(lvl, lvlRegex);
assert.match(msg, msgRegex);
});
test('file should contain correct message', () => {
const level = levels[
Math.floor(Math.random() * levels.length)
];
const message = Math.random().toString();
const logMessage = log_message(fileName, message, level);
const fileMessage = fs.readFileSync(fileName, 'utf8');
assert.strictEqual(logMessage, fileMessage);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment