JavaScript: Account Transactions
Create a solution to maintain a bank account’s balance.
Implement the Account class that manages an account’s balance. The class has the following constructor and methods:
- The constructor Account(balance) where parameter balance denotes the initial balance of the account.
- The method debit(amount) debits the amount from the account and returns true.
If insufficient balance, do not debit and return false. - The method getBalance() returns the current balance.
- The method credit(amount) credits the amount to the account.
NOTE: You may assume that the amount parameter passed is always positive or 0.
The locked stub code validates the correctness of the Account class implementation by performing the following operations:
Debit amount. This operation debits the amount. If the return value is false, it prints ‘Insufficient balance’. Otherwise it prints ‘<amount>debited’.
Credit amount. This operation credits the amount and prints ‘<amount>credited’.
GetBalance: This operation gets the current balance and prints ‘Current balance is <balance>’.


Solution Implementation
"use strict";
const fs = require("fs");
process.stdin.resume();
process.stdin.setEncoding("ascii");
let inputString = "";
let currentLine = 0;
process.stdin.on("data", function (chunk) {
inputString += chunk;
});
process.stdin.on("end", function () {
inputString = inputString.split("\n");
main();
});
function readLine() {
return inputString[currentLine++];
}
class Account {
constructor(balance) {
this.balance = balance;
}
debit = (amount) => {
if (this.balance < amount) return false;
this.balance -= amount;
return true;
};
credit = (amount) => {
this.balance += amount;
return true;
};
getBalance = () => this.balance;
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const initialBalance = parseInt(readLine().trim());
const accountObj = new Account(initialBalance);
ws.write(`Account created with initial balance of ${initialBalance}\n`);
let numberOfOperations = parseInt(readLine().trim());
while (numberOfOperations-- > 0) {
const inputs = readLine().trim().split(" ");
const operation = inputs[0];
const amount = parseInt(inputs[1]);
switch (operation) {
case "Debit":
if (accountObj.debit(amount)) {
ws.write(`${amount} debited\n`);
} else {
ws.write(`Insufficient balance\n`);
}
break;
case "Credit":
accountObj.credit(amount);
ws.write(`${amount} credited\n`);
break;
case "GetBalance":
const currentBalance = accountObj.getBalance();
ws.write(`Current balance is ${currentBalance}\n`);
default:
break;
}
}
ws.end();
}
JavaScript: Data Finder
Implement the function dataFinder such that:
· It takes a single argument data, an array of integers.
. It returns a new function that is called find.
Find takes 3 arguments: minRange (Integer), maxRange (Integer) and value (Integer). It performs the following:
It searches for the value in the data array in the inclusive range [minRange -maxRange] using 0-based indexing.
If value is found in the given range, it returns true. Otherwise it returns false.
If minRange or maxRange is beyond an end of the array, throws an Error object with the message of ‘Invalid range’.
For example, calling dataFinder([1, 6, 3, 0, 2, 15, 10]) must return a function find, such that calling find(2,4,10) returns false. It searches for 10 in the inclusive range 2 through 4, the subarray [3, 0, 2]. It is not found in the given range as it lies at index 6. So the function returns false.
The implementation will be tested by a provided code stub using several input files with parameters. The dataFinder function will be called with the data parameter, and then the returned function will be called with the minRange, maxRange, and value parameters. The result will be printed to the standard output by the provided code.
Constraints:
The maximum length of the passed array is 10.


Solution Implementation
"use strict";
const fs = require("fs");
process.stdin.resume();
process.stdin.setEncoding("ascii");
let inputString = "";
let currentLine = 0;
process.stdin.on("data", function (chunk) {
inputString += chunk;
});
process.stdin.on("end", function () {
inputString = inputString.split("\n");
main();
});
function readLine() {
return inputString[currentLine++];
}
function dataFinder(data) {
var find = function (minRange, maxRange, value) {
if (minRange < 0 || maxRange >= data.length) {
throw new Error("Invalid range");
}
for (let i = minRange; i <= maxRange; i++) {
if (data[i] === value) {
return true;
}
}
return false;
};
return find;
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const data = readLine().trim().split(" ");
const finalData = data.map((val) => parseInt(val));
const join = dataFinder(finalData);
try {
const inputs = readLine().trim().split(" ");
const result = join(
parseInt(inputs[0]),
parseInt(inputs[1]),
parseInt(inputs[2])
);
ws.write(result.toString());
} catch (e) {
ws.write(`${e}`);
}
ws.end();
}
Joinned Logger
"use strict";
const fs = require("fs");
process.stdin.resume();
process.stdin.setEncoding("utf-8");
let inputString = "";
let currentLine = 0;
process.stdin.on("data", function (inputStdin) {
inputString += inputStdin;
});
process.stdin.on("end", function () {
inputString = inputString.split("\n");
main();
});
function readLine() {
return inputString[currentLine++];
}
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
function logger(msg) {
ws.write(`${msg.text}\n`);
}
function joinedLogger(level, sep) {
// write your code here
return function f(...messages) {
let str = "";
messages.forEach((msg) => {
if (msg.level >= level) {
str = str + msg.text + sep;
}
});
let len = sep.length;
let strArray = str.split("");
strArray.splice(strArray.length - len, len);
str = strArray.join("");
console.log({ str, messages, level, sep });
fs.createWriteStream(process.env.OUTPUT_PATH).write(str);
return;
};
}
function main() {
const firstLine = readLine().trim().split(" ");
const level = parseInt(firstLine[0]);
const sep = firstLine[1];
const myLog = joinedLogger(level, sep);
const n = parseInt(readLine().trim());
let messages = [];
for (let i = 0; i < n; ++i) {
const line = readLine().trim().split(" ");
const level = parseInt(line[0]);
const text = line[1];
messages.push({ level, text });
}
myLog(...messages);
ws.end();
}
Notes Store
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function (inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function () {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
const completedNotes = [];
const activeNotes = [];
const otherNotes = [];
class NotesStore {
addNote(state, name) {
if (name === undefined || name === null || name === '') {
throw new Error('Name cannot be empty');
}
if (!this.isValid(state)) {
throw new Error('Invalid state ' + state);
}
this.getNotesList(state).push(name);
}
getNotes(state) {
if (!this.isValid(state)) {
throw new Error('Invalid state ' + state);
}
return this.getNotesList(state);
}
getNotesList(state) {
if (state === 'completed') {
return completedNotes;
} else if (state === 'active') {
return activeNotes;
}
return otherNotes;
}
isValid(state) {
return state === 'completed'
|| state === 'active'
|| state === 'others';
}
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const obj = new NotesStore();
const operationCount = parseInt(readLine().trim());
for (let i = 1; i <= operationCount; i++) {
const operationInfo = readLine().trim().split(' ');
try {
if (operationInfo[0] === 'addNote') {
obj.addNote(operationInfo[1], operationInfo[2] || '');
} else if (operationInfo[0] === 'getNotes') {
const res = obj.getNotes(operationInfo[1]);
if (res.length === 0) {
ws.write('No Notes\n');
} else {
ws.write(`${res.join(',')}\n`);
}
}
} catch (e) {
ws.write(`${e}\n`);
}
}
ws.end();
}
Order List Processing
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding("ascii");
let inputString = "";
let currentLine = 0;
process.stdin.on("data", function (chunk) {
inputString += chunk;
});
process.stdin.on("end", function () {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
function processOrderList(orderList, orderId, state) {
// Write your code here
return state === 'Processing' ?
orderList.map(item => ({
...item,
state: item.id === orderId ? 'Processing' : item.state
})) :
orderList.filter(item => item.id !== orderId);
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const orderCount = parseInt(readLine().trim());
let orderList = [];
for (let i = 0; i < orderCount; i++) {
orderList.push({
id: i + 1,
state: 'Received'
})
};
let numberOfOperations = parseInt(readLine().trim());
let updatedOrderList = [...orderList];
while (numberOfOperations-- > 0) {
const inputs = readLine().trim().split(' ');
const orderId = parseInt(inputs[0]);
const updatedState = inputs[1];
updatedOrderList = processOrderList(updatedOrderList, orderId, updatedState);
updatedOrderList = [...updatedOrderList];
}
if (updatedOrderList.length > 0) {
for (let i = 0; i < updatedOrderList.length; i++) {
const order = updatedOrderList[i];
ws.write(`Order with id ${order.id} is in ${order.state} state\n`);
};
} else {
ws.write(`All orders are in Delivered state\n`);
}
ws.end();
}
The Above Solution Help you to get the Certificate in JavaScript Basic