Skip to content

Instantly share code, notes, and snippets.

@ifindev
Last active August 4, 2024 19:47
Show Gist options
  • Save ifindev/b7589643f343269d91bcc5a8ef8df4fc to your computer and use it in GitHub Desktop.
Save ifindev/b7589643f343269d91bcc5a8ef8df4fc to your computer and use it in GitHub Desktop.
REST API Transaction by Average Monthly Spending
'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++];
}
/*
* Complete the 'getUserTransaction' function below.
*a
* The function is expected to return an INTEGER_ARRAY.
* The function accepts following parameters:
* 1. INTEGER uid
* 2. STRING txnType
* 3. STRING monthYear
*
* https://jsonmock.hackerrank.com/api/transactions/search?userId=
*/
const axios = require('axios');
function getMonthYear(monthYear) {
const date = monthYear.split("-")
const month = parseInt(date[0])
const year = parseInt(date[1])
return {"month":month, "year":year}
}
function convertAmountToNum(amount) {
const numAmount = parseFloat(amount.replace("$","").replace(",",""))
return numAmount
}
async function getSpecificApiData(url, dataKey) {
const response = await axios.get(url)
const data = response.data[dataKey]
return data
}
async function getAllPaginatedData(uid, txnType, totalPages) {
let url = `https://jsonmock.hackerrank.com/api/transactions/search?userId=${uid}&txnType=${txnType}&page=`
let allData = []
for (let i = 0; i < totalPages; i++) {
let curURL = `${url}${i+1}`
const data = await getSpecificApiData(curURL, 'data')
allData = [...allData, ...data]
}
return allData
}
async function getTotalPages(uid, txnType) {
let url = `https://jsonmock.hackerrank.com/api/transactions/search?userId=${uid}&txnType=${txnType}`
const totalPages = await getSpecificApiData(url, 'total_pages')
return totalPages
}
async function getTrxDataByTotalPages(uid, txnType) {
const totalPages = await getTotalPages(uid, txnType)
const data = await getAllPaginatedData(uid, txnType, totalPages)
return data
}
function filterTrxDataByDate(data, refDate) {
const filtered = data.filter(dat => {
const tsDate = new Date(dat.timestamp)
const date = {"month": tsDate.getMonth() + 1, "year": tsDate.getFullYear()}
if(date.month === refDate.month && date.year === refDate.year) {
return dat
}
})
return filtered
}
/**
* uid: int
* refDate : {"month":int, "year":int}
*/
async function getAverageMonthlyTrx(uid, refDate) {
const debitData = await getTrxDataByTotalPages(uid, 'debit')
const spendingData = filterTrxDataByDate(debitData, refDate)
const monthlySpending = spendingData.reduce((total, spending) => total + convertAmountToNum(spending.amount), 0)
const averageMonthlySpending = monthlySpending / spendingData.length
return averageMonthlySpending
}
async function getTrxLargerThanAvgMonthlySpending(uid, txnType, refDate, averageSpending) {
const trxData = await getTrxDataByTotalPages(uid, txnType)
const filtered = filterTrxDataByDate(trxData, refDate)
const validIds = filtered.filter(data => {
const amount = convertAmountToNum(data.amount)
if(amount > averageSpending) {
return data
}
}).map(dat => {
return dat.id
})
validIds.sort(function(a, b){return a - b})
return validIds
}
async function getUserTransaction(uid, txnType, monthYear) {
const refDate = getMonthYear(monthYear)
try {
const averageMonthly = await getAverageMonthlyTrx(uid, refDate)
const validTrxIds = await getTrxLargerThanAvgMonthlySpending(uid, txnType, refDate, averageMonthly)
return validTrxIds.length > 0 ? validTrxIds : [-1]
} catch(err) {
console.error(err)
return [-1]
}
}
async function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const uid = parseInt(readLine().trim(), 10);
const txnType = readLine();
const monthYear = readLine();
const result = await getUserTransaction(uid, txnType, monthYear);
ws.write(result.join('\n') + '\n');
ws.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment