In checkData method I am checking 2 API's status as fulfilled or rejected and based on that I am sending API Data and FailFlag. How can i optimize it as I have used if else statements.
const checkData = (data, allData, failFlag) => {
if (data && data[0].status === 'fulfilled' && data[1].status === 'fulfilled') {
if (data[0].value && data[1].value) {
allData.push(...data[0].value, ...data[1].value);
failFlag = 'NONE';
}
} else if (data[0].status === 'rejected' && data[1].status === 'fulfilled') {
allData.push(...data[1].value);
failFlag = 'INTERNAL';
} else if (data[0].status === 'fulfilled' && data[1].status === 'rejected') {
allData.push(...data[0].value);
failFlag = 'EXTERNAL';
console.log('All data with fail flag', allData, failFlag);
} else {
Promise.reject('Both are rejected');
failFlag = 'ALL';
}
return { errorFlag: failFlag, accounts: allData };
};
I'm not sure why you are passing in failFlag, because you're never using that variable. I'm also not sure why you have written Promise.reject('Both are rejected');. However, the code can be simplified as follows:
const checkData = ([{status:s0, value:v0}, {status:s1, value:v1}]=[{},{}], allData) => {
let errorFlag = 'NONE';
let f0 = s0 === 'fulfilled';
let f1 = s1 === 'fulfilled';
if(f0) allData.push(...v0);
if(f1) allData.push(...v1);
if(!f0 && !f1) errorFlag = 'ALL';
if(!f0 && f1) errorFlag = 'INTERNAL';
if( f0 && !f1) errorFlag = 'EXTERNAL';
return { errorFlag, accounts: allData };
};
Related
hi i am trying to implement a local orderbook using the binance api however i keep getting this error every now and then it does not always happen but if it does it will happen early on please help
this is the main file that runs calling an exports function from an external file to process the data coming from the web socket on message
wsClient.subscribeSpotDiffBookDepth("btcusdt");
wsClient.on('message', (data) => {
// Setup and process order book information
order_book.update_orderbook(data);
if(order_book.ready === 1){
order_book.get_orderbook_history();
}
});
wsClient.on('error', err => {
/* handle error */
console.log("this is it 2 " + err);
});
wsClient.on('close', () => {
/* ... */
});
exports function in external file
exports.update_orderbook = function(data) {
if(data.e == "depthUpdate"){
if(this.ready === 0){
this.ready = 1;
console.log("Stage 1 in play");
}else{
this.buffer += data;
}
if(this.ready === 2 && this.asks != null && this.bids != null){
if(undefined !== this.asks && undefined !== this.bids && undefined !== data.a && undefined !== data.b){
if(data.U <= this.lastUpdateId + 1 && data.u >= this.lastUpdateId + 1){
// error is coming from calling this function-------------------------------------------------------
var temp_array1 = sort_array(this.asks, data.a);
var temp_array2 = sort_array(this.bids, data.b);
this.asks = temp_array1;
this.bids = temp_array2;
this.lastUpdateId = data.u;
console.log("Stage 3");
}
}
}else{
this.buffer += data;
}
}
}
function to sort and update the array
function sort_array(array1, array2){
for(let x in array2){
if(array2[x][1] == 0){
for(let i in array2){
if(array1[i][0] === array2[x][0]){
array1.splice(i, 1);
}
}
}else{
var in_array = false;
for(let i in array1){
// this seems to be the problem area---------------------------------------------------------
if(array1[i][0] === array2[x][0]){
array1[i] = array2[x];
in_array = true;
}
}
if(!in_array){
array1.push(array2[x]);
}
}
}
return array1;
}
error log
I have a variable called
let idStatus = '';
I need my getValues function to return true and am using this variable to determine whether it returns true or false.
function getValues(){
let idStatus = '';
let getValuesUrl = 'https://something.something.com/v1.0/something/1?apiKey=1234abcdefghijklmnop';
const getValuesRequest = new XMLHttpRequest();
getValuesRequest.responseType = 'json';
getValuesRequest.open('GET', getOptionValuesUrl);
getValuesRequest.send();
getValuesRequest.onreadystatechange = function () {
const response = getValuesRequest.response;
if (response) {
if (getValuesRequest.status == 200) {
console.log('Success');
if(validateIds(response)){
console.log('ID is Valid');
idStatus = true;
}
else {
console.log('ID is NOT Valid');
idStatus = false;
}
}
}
console.log(idStatus);
return idStatus;
}
function validateIds(obj) {
const data = obj['data'];
console.log(data);
let validId = '';
for (let i = 0; i < data.length; i++) {
if (data[i].id == 1) {
validId = true;
}
else {
validId = false;
}
}
console.log(validId);
return validId;
}
Valid IDs runs the way it should and getValues console.logs the appropriate responses when it is true or false, yet idStatus always returns null.
Here I've made a simpler version of your code. I used axios instead of XMLHttpRequest as it's simpler to use.
const axios = require("axios");
async function getValues(link) {
const response = await axios.get(link);
if (!response.statusCode == 200) return false;
if (response.data.some(elm => elm.id != 1)) return false;
return true;
}
// if the status isn't 200, return false;
if (!response.statusCode == 200) return false;
// if one id isn't 1, return false;
if (response.data.some(elm => elm.id != 1)) return false;
If you want more details on Array.some(), here's a link Array.Some()
I have a class with a method for which I'm building a test with JEST.
The below snippet shows what I want to test.
I would like to test for example c5 and I would like to check there what will happen if the length === 0 or length === 2 as the specific result should happen only with length === 1
I already built tests for other cases as follow
test('C1 - is default, same country, active', async () => {
try {
const service = serviceWithDAO({ sites: Data.mock});
const defaultSite = await service.getDefaultSite({ studyId: 'DEFAULT1', locale: 'us_ES'});
console.log('C1', defaultSite);
expect(defaultSite.default).toBeTruthy();
expect(defaultSite.countryCode).toEqual('es');
expect(defaultSite.status).toEqual('ACTIVE');
expect(defaultSite.siteId).toEqual('site 1');
} catch (e) {
console.error(e.message);
}
});
The above test passes as expected but I have doubts about how can I test what result to expect in case 5 as described that case should have length === 1 and I want to test a fail case.
below is the method and I'm interested in how should I do a test for C5 case
class SiteService extends ServiceBase {
getDefaultSite({ studyId, locale }) {
return this.withDAO(async ({ sites }) => {
const sitesStudy = await sites.select({ studyId });
if (!sitesStudy || !sitesStudy.length) return undefined;
const countryCode = locale.substr(3, 4).toLowerCase();
const c1 = sitesStudy.filter(
site =>
site.default &&
site.countryCode === countryCode &&
site.status === 'ACTIVE'
);
console.log('C1', c1);
if (c1[0]) return c1[0];
const c2 = sitesStudy.filter(
site =>
site.default &&
site.countryCode === countryCode &&
site.status === 'INACTIVE'
);
console.log('C2', c2);
if (c2[0]) return c2[0];
console.log(
sitesStudy.filter(
site =>
site.default &&
site.countryCode !== countryCode &&
site.status === 'ACTIVE'
),
countryCode
);
const c3 = sitesStudy.filter(
site =>
site.default &&
site.countryCode !== countryCode &&
site.status === 'ACTIVE'
);
console.log('C3', c3);
if (c3[0]) return c3[0];
const c4 = sitesStudy.filter(
site =>
site.default &&
site.countryCode !== countryCode &&
site.status === 'INACTIVE'
);
console.log('C4', c4);
if (c4[0]) return c4[0];
const c5 = sitesStudy.filter(site => site.status === 'ACTIVE');
console.log('C5', c5);
if (c5.length === 1) return c5[0];
return null;
});
}
}
Service base
function ServiceBase(ctx) {
let key;
let value;
for ([key, value] of Object.entries(ctx)) {
this[key] = value;
}
}
ServiceBase.prototype.constructor = ServiceBase;
module.exports = ServiceBase;
I got a click event attached to a button to perform a search that checks if a certain element matches a certain condition. In the snippet below there is a some() array method that checks the 'entriesFound' array for the element that matches a certain condition. However everything works find till the else if(el.name !== name.value) condition. The alertbox shows but I need to click the OK button in the alertbox as many times as there are elements in the entriesFound array.
import { persons } from './main.js';
export let entriesFound = []
export const searchBtn = document.querySelector('.search').addEventListener('click' , function() {
let name = document.querySelector('.searchInput')
if(name.value === "") {
alert('No search query!')
return;
}
entriesFound.some( el => {
if(el.name === name.value){
name.value = ""
alert("You\'ve already found what you are looking for!")
el.remove();
// from here things go wrong
}else if(el.name !== name.value){
alert("No data found!")
return;
}
})
persons.some( el => {
if(el.name === name.value) {
addItem(el)
entriesFound.push(el);
}
})
name.value = ""
localStorage.setItem('entriesFound', JSON.stringify(entriesFound))
})
You should use the return value of some and you can utilize find:
import { persons } from "./main.js";
export let entriesFound = [];
export const searchBtn = document
.querySelector(".search")
.addEventListener("click", function () {
let name = document.querySelector(".searchInput");
if (name.value === "") {
alert("No search query!");
return;
}
const entryExists = entriesFound.some((el) => el.name === name.value);
if (entryExists) {
name.value = "";
alert("You've already found what you are looking for!");
el.remove();
// from here things go wrong
} else {
alert("No data found!");
return;
}
const item = persons.find(el.name === name.value);
if (item !== null) {
addItem(item);
entriesFound.push(item);
}
name.value = "";
localStorage.setItem("entriesFound", JSON.stringify(entriesFound));
});
Thanks all of you. I combined your solutions. I used regular for loops and the every() array method.
import { persons } from "./main.js";
export let entriesFound = [];
export const searchBtn =
document.querySelector('.search').addEventListener('click' , () => {
let name = document.querySelector('.searchInput')
if(name.value === "") {
alert('No search query!')
return;
}
if(entriesFound.length > 0){
for(let el of entriesFound){
if(el.name === name.value) {
alert('You have found that one already!')
name.value = ""
return;
}
}
}
if(persons.length > 0 ){
for(let el of persons) {
if(el.name === name.value) {
addItem(el)
entriesFound.push(el)
}
}
}else if(persons.length === 0 ){
alert('No data!')
name.value = ""
return;
}
let noMatch = persons.every( el => el.name !== name.value)
console.log(noMatch)
if(noMatch === true){
alert('No match!');
name.value = ""
return;
}
name.value = ""
localStorage.setItem('entriesFound', JSON.stringify(entriesFound))
});
I currently have this code built in JS, but it's really, really ugly.
Is there any better way to approach it?
The way it works basically is pushing a string like app.chat.test to be the key, and value like teststr.
I test the lengths to see if the "parent" key is there, otherwise we build it.
function constructJson(jsonKey, jsonValue){
//REWRITE!!!!!!!!
let jsonObj = langFile;
let jsonKeyArr = jsonKey.split('.')
if (jsonKeyArr.length === 1) {
if (valToAdd === undefined) {
if (jsonObj[jsonKey] === undefined) {
jsonObj[jsonKey] = {}
}
} else {
if (jsonObj[jsonKey] === undefined) {
jsonObj[jsonKey] = valToAdd
}
}
} else if (jsonKeyArr.length === 2) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = jsonValue
}
} else if (jsonKeyArr.length === 3) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = jsonValue
}
} else if (jsonKeyArr.length === 4) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] = jsonValue
}
} else if (jsonKeyArr.length === 5) {
if (jsonObj[jsonKeyArr[0]] === undefined) {
jsonObj[jsonKeyArr[0]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]] = {}
}
if (jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]][jsonKeyArr[4]] === undefined) {
jsonObj[jsonKeyArr[0]][jsonKeyArr[1]][jsonKeyArr[2]][jsonKeyArr[3]][jsonKeyArr[4]] = jsonValue
}
} else if (jsonKeyArr.length > 5) {
return console.log("Length over 5 not supported yet!")
}
return jsonObj;
}
Regards.
OF course it's possible, a simple loop will perfeclty do the job.
function constructJson(jsonKey, jsonValue){
//REWRITE!!!!!!!!
langFile = {a:{}, foo:{}};// remove this for your own code
var jsonObj = langFile;
var jsonKeyArr = jsonKey.split('.');
var currentValue = jsonObj;
for(var i = 0; i < jsonKeyArr.length;i++){
if(currentValue[jsonKeyArr[i]]===undefined){
currentValue[jsonKeyArr[i]] = {};
}
if(i < jsonKeyArr.length-1){
currentValue = currentValue[jsonKeyArr[i]];
}else{
currentValue[jsonKeyArr[i]] = jsonValue;
}
}
return jsonObj;
}
alert(JSON.stringify(constructJson("a.b.cd.ef", "toto")));
I just assigning to a temporary variable each sublevel. When i'm on the last i'm assigning the value.
Yes you can, using the javascript reduce function on the array created from the splitted string.
function namespaceCreateExceptLast(representationOfElementToCreate, baseNamespace) {
var tokens;
if (typeof representationOfElementToCreate !== 'string')
throw new Error('Expecting string as first parameter');
if (baseNamespace === undefined)
baseNamespace = window;
tokens = representationOfElementToCreate.split('.');
// Remove the last element (which will contain the value)
tokens.pop();
// Use reduce to create part by part your new object
return tokens.reduce(function (prev, property) {
if (typeof prev !== 'object') {
throw Error('One property is already defined but not an object, namespace creation has failed', property);
return undefined;
} else {
if (!prev[property])
prev[property] = {};
return prev[property];
}
}, baseNamespace);
};
Then you can have:
function constructJson(jsonKey, jsonValue){
let jsonObj = langFile;
var lastItem = namespaceCreateExceptLast(jsonKey, jsonObj);
var lastKey = jsonKey.substring(jsonKey.lastIndexOf('.') + 1);
lastItem[lastKey] = jsonValue;
}
I have added some comments and exceptions to help you understand how it's done, but it's mainly based on the reduce function which you can easily get help for (https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/reduce).