How to test loop with jest? - jestjs

I am new to jest. There is a task to test a cycle.
let values = [];
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
values.push("fizzbuzz");
} else if (i % 3 === 0) {
values.push("fizz");
} else if (i % 5 === 0) {
values.push("buzz");
} else {
values.push("-");
}
}
I did the following.
require("./fizzBuzzLoop");
describe("loop for with fizzbuzz", () => {
let values = [];
test("define a conditions for string values in loop", () => {
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
values.push("fizzbuzz");
expect(values).toContain("fizzbuzz");
} else if (i % 3 === 0) {
values.push("fizz");
expect(values).toContain("fizz");
} else if (i % 5 === 0) {
values.push("buzz");
expect(values).toContain("buzz");
} else {
values.push("-");
expect(values).toContain("-");
}
}
});
});
I don't fully understand how the loop should be tested. I will be grateful for help

You don't need to write a loop in the test. Wrap the action in a function, run it in the test and offer a comparison option for the result of the function.
For example:
function fizzBuzz(n=100) {
let values = [];
for (let i = 1; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
values.push("fizzbuzz");
} else if (i % 3 === 0) {
values.push("fizz");
} else if (i % 5 === 0) {
values.push("buzz");
} else {
values.push("-");
}
}
return values
}
And the test looks like:
require("./fizzBuzzLoop");
describe("loop for with fizzbuzz", () => {
test("define a conditions for string values in loop", () => {
expect(fizzBuzz(15)).toEqual([ '-',
'-',
'fizz',
'-',
'buzz',
'fizz',
'-',
'-',
'fizz',
'buzz',
'-',
'fizz',
'-',
'-',
'fizzbuzz' ]);
});
});

I found a more general way
let values = [];
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
values.push("fizzbuzz");
} else if (i % 3 === 0) {
values.push("fizz");
} else if (i % 5 === 0) {
values.push("buzz");
} else {
values.push("-");
}
}
module.exports = values;
The solution to the problem is done in the forehead. But you can reduce the number of tests and check the entire array for compliance at once.
const values = require('./fizzBuzzLoop');
const expected = ['-',
'-',
'fizz',
'-',
'buzz',
'fizz',
'-',
'-',
'fizz',
'buzz',
'-',
'fizz',
'-',
'-',
'fizzbuzz',
'-',
'-',
'fizz',
'-',
'buzz',
'fizz',
'-',
'-',
'fizz',
'buzz',
'-',
'fizz',
'-',
'-',
'fizzbuzz',
'-',
'-',
'fizz',
'-',
'buzz',
'fizz',
'-',
'-',
'fizz',
'buzz',
'-',
'fizz',
'-',
'-',
'fizzbuzz',
'-',
'-',
'fizz',
'-',
'buzz',
'fizz',
'-',
'-',
'fizz',
'buzz',
'-',
'fizz',
'-',
'-',
'fizzbuzz',
'-',
'-',
'fizz',
'-',
'buzz',
'fizz',
'-',
'-',
'fizz',
'buzz',
'-',
'fizz',
'-',
'-',
'fizzbuzz',
'-',
'-',
'fizz',
'-',
'buzz',
'fizz',
'-',
'-',
'fizz',
'buzz',
'-',
'fizz',
'-',
'-',
'fizzbuzz',
'-',
'-',
'fizz',
'-',
'buzz',
'fizz',
'-',
'-',
'fizz',
'buzz'];
describe("loop for with fizzbuzz", () => {
test("check array for matching values", () => {
expect(expected).toEqual(values);
});
});

Related

Update list of Objects with a value from an array

I had an issue earlier and received some help with it earlier but now i'm having an issue updating/adding a link to earlier issue.
I have a slightly different setup at this point because i couldn't figure out how to update my data.
At this point. I need to get the data from my Array A (filepath) into my list of objects as another property in my sub object with a key of "-i".
I feel like i should be able to iterate through the array and add one of these values to my object but i've tried using the reduce and loop features but haven't been able to get my desired output, if there's a easier way from starting with my last post issue i'd be happy to go back to that state.
//Desired ouput
{
process0000x0000: {-i:"D:\\Code\\UnitTest\\Tests\\Run_01_TEMP\\0000x0000.png, tr: 16, tc: 16, ofr: 16, ofc: 16, outfile: 'D:\\Code\\Process\\1' },
process0000x0001: {-i:"D:\\Code\\UnitTest\\Tests\\Run_01_TEMP\\0000x0001.png", tr: 16, tc: 16, ofr: 16, ofc: 16, outfile: 'D:\\Code\\Process\\1' },
process0000x0002: {-i:"D:\\Code\\UnitTest\\Tests\\Run_01_TEMP\\0000x0002.png", tr: 16, tc: 16, ofr: 16, ofc: 16, outfile: 'D:\\Code\\Process\\1' }
}
//Array A
"outputParameters": [
{
"name": "0000x0000",
"filepath": "D:\\Code\\UnitTest\\Tests\\Run_01_TEMP\\0000x0000.png"
},
{
"name": "0000x0001",
"filepath": "D:\\Code\\UnitTest\\Tests\\Run_01_TEMP\\0000x0001.png"
},
{
"name": "0000x0002",
"filepath": "D:\\Code\\UnitTest\\Tests\\Run_01_TEMP\\0000x0002.png"
}]
// current output
{
process0000x0000: { tr: 16, tc: 16, ofr: 16, ofc: 16, outfile: 'D:\\Code\\Process\\1' },
process0000x0001: { tr: 16, tc: 16, ofr: 16, ofc: 16, outfile: 'D:\\Code\\Process\\1' },
process0000x0002: { tr: 16, tc: 16, ofr: 16, ofc: 16, outfile: 'D:\\Code\\Process\\1' }
}
UPDATE:
so i added the below but i'm still receiving the last "filepath" for each entry in my consoleparamscompiled data. I tried your way and the way i have shown below but with the same results.
//results
},
process13x21: {
'-i': 'D:\\Code\\UnitTest\\ConsoleApp\\1\\13x23.png',
'-tr': 16,
'-tc': 16,
'-ofr': 16,
'-ofc': 16,
'-outfile': '"D:\\Code\\UnitTest\\ConsoleApp\\Process\\1"'
},
process13x22: {
'-i': 'D:\\Code\\UnitTest\\ConsoleApp\\1\\13x23.png',
'-tr': 16,
'-tc': 16,
'-ofr': 16,
'-ofc': 16,
'-outfile': '"D:\\Code\\UnitTest\\ConsoleApp\\Process\\1"'
},
process13x23: {
'-i': 'D:\\Code\\UnitTest\\ConsoleApp\\1\\13x23.png',
'-tr': 16,
'-tc': 16,
'-ofr': 16,
'-ofc': 16,
'-outfile': '"D:\\Code\\UnitTest\\ConsoleApp\\Process\\1"'
}
}
// ADDED CODE
// loop through each data we want to add and add a property.
` consoleOutputParamsOBJ.forEach((obj) => {
var processname = dynamicTaskNameBaseOBJ + obj.name;
console.log(processname);
//taskparamscompiled.processname['-i'] = obj.filepath;
taskparamscompiled[processname]['-i'] = obj.filepath;
// console.log(dynamicTaskNameBaseOBJ + obj.name);
});
console.log(taskparamscompiled);`
I'm not 100% sure I understand your question, but here goes.
You can access an objects property by a string by using [] instead of .
E.g.
let x = {name: "chris"};
x.name = 'Sam';
x['name'] = 'Ben';
The above will both change the name property
Here is a code example with the data you provided.
let data = [{
"name": "0000x0000",
"filepath": "D:\\Code\\UnitTest\\Tests\\Run_01_TEMP\\0000x0000.png"
}, {
"name": "0000x0001",
"filepath": "D:\\Code\\UnitTest\\Tests\\Run_01_TEMP\\0000x0001.png"
}, {
"name": "0000x0002",
"filepath": "D:\\Code\\UnitTest\\Tests\\Run_01_TEMP\\0000x0002.png"
}];
let result = {
process0000x0000: {
tr: 16,
tc: 16,
ofr: 16,
ofc: 16,
outfile: 'D:\\Code\\Process\\1'
},
process0000x0001: {
tr: 16,
tc: 16,
ofr: 16,
ofc: 16,
outfile: 'D:\\Code\\Process\\1'
},
process0000x0002: {
tr: 16,
tc: 16,
ofr: 16,
ofc: 16,
outfile: 'D:\\Code\\Process\\1'
}
}
// loop through each data we want to add and add a property.
data.forEach(obj => {
result[`process${obj.name}`]["-i"] = obj.filepath
})
console.log(result)
And the output is :
{
process0000x0000: {
-i: "D:\Code\UnitTest\Tests\Run_01_TEMP\0000x0000.png",
ofc: 16,
ofr: 16,
outfile: "D:\Code\Process\1",
tc: 16,
tr: 16
},
process0000x0001: {
-i: "D:\Code\UnitTest\Tests\Run_01_TEMP\0000x0001.png",
ofc: 16,
ofr: 16,
outfile: "D:\Code\Process\1",
tc: 16,
tr: 16
},
process0000x0002: {
-i: "D:\Code\UnitTest\Tests\Run_01_TEMP\0000x0002.png",
ofc: 16,
ofr: 16,
outfile: "D:\Code\Process\1",
tc: 16,
tr: 16
}
}

how to create an object from a python array

I have the following structure, which I convert from a .txt with pandas
[[000001, 'PEPE ', 'S', 'LAST_NAME ', 'CIP ', 'CELLPHONE'],
[0000002, 'LUIS ', 'S', 'ADRESS ', ' ', 'nan'],
[0000003, 'PEDRO ', 'S', 'STREET ', 'CITY', ' nan']]
My code
import pandas as pd
file = 'C:\\Users\\Admin\\Desktop\\PRUEBA.txt'
columns = ("service", "name", "Active", "reference1", "reference2", "reference3")
df = pd.read_csv(file, sep="|", names=columns, header=None)
cl = df.values.tolist()
print(cl)
but to be able to give it the treatment, which it requires, either by removing the empty strings and nan, how can I transform the service to int and create an object based on the service and the references in this way.
[
{ service: 1, name: 'PEPE', order: 0, ref: 'LAST_NAME' },
{ service: 1, name: 'PEPE', order: 1, ref: 'CIP' },
{ service: 1, name: 'PEPE', order: 2, ref: 'CELLPHONE' },
{ service: 2, name: 'LUIS', order: 0, ref: 'ADRESS' },
{ service: 3, name: 'PEDRO', order: 0, ref: 'STREET' },
{ service: 3, name: 'PEDRO', order: 1, ref: 'CITY' }
]
How can I achieve this, very grateful for your comments
Key: Use df.melt() to unpivot the table and subsequently perform df.to_dict(orient='records') to convert the dataframe to a record-oriented dict as mentioned by #QuangHoang. The rest are regular filtering and miscellaneous adjustments.
# data
ls = [['000001', 'PEPE ', 'S', 'LAST_NAME ', 'CIP ', 'CELLPHONE'],
['0000002', 'LUIS ', 'S', 'ADRESS ', ' ', 'nan'],
['0000003', 'PEDRO ', 'S', 'STREET ', 'CITY', ' nan']
]
df = pd.DataFrame(ls, columns=("service", "name", "Active", "reference1", "reference2", "reference3"))
# reformat and strip over each column
for col in df:
if col == "service":
df[col] = df[col].astype(int)
else:
df[col] = df[col].str.strip() # accessor
# unpivot and adjust
df2 = df.melt(id_vars=["service", "name"],
value_vars=["reference1", "reference2", "reference3"],
value_name="ref")\
.sort_values(by="service")\
.drop("variable", axis=1)\
.reset_index(drop=True)
# filter out empty or nan
df2 = df2[~df2["ref"].isin(["", "nan"])]
# generate order numbering by group
df2["order"] = df2.groupby("service").cumcount()
df2 = df2[["service", "name", "order", "ref"]] # reorder
# convert to a record-oriented dict
df2.to_dict(orient='records')
Out[99]:
[{'service': 1, 'name': 'PEPE', 'order': 0, 'ref': 'LAST_NAME'},
{'service': 1, 'name': 'PEPE', 'order': 1, 'ref': 'CIP'},
{'service': 1, 'name': 'PEPE', 'order': 2, 'ref': 'CELLPHONE'},
{'service': 2, 'name': 'LUIS', 'order': 0, 'ref': 'ADRESS'},
{'service': 3, 'name': 'PEDRO', 'order': 0, 'ref': 'STREET'},
{'service': 3, 'name': 'PEDRO', 'order': 1, 'ref': 'CITY'}]

Format data for high charts representation

I have data in the below format. I want to plot a line chart to compare data for years 2017 and 2018 for al the months with total.
const listItems = [{
"id": 1,
"total": 21.15,
"dat": "2017-10-21T08:32:36.000Z"
},
{
"id": 2,
"total": 22,
"dat": "2017-11-24T13:46:16.000Z"
},{
"id": 3,
"total": 11,
"dat": "2017-11-24T13:46:16.000Z"
},
{
"id": 4,
"total": 12,
"dat": "2018-04-02T09:15:35.000Z",
}
]
i want to represent Line chart in the below format :
var xAxis = {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
]
};
var series = [{
name: '2017',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2,
26.5, 23.3, 18.3, 13.9, 9.6
]
},
{
name: '2018',
data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8,
24.1, 20.1, 14.1, 8.6, 2.5
]
}
];
basically the data represents sum of all the months .
First, write a function that mines month from date, for example:
var dateToMonth = (date) => {
var matched = /[\d]{4}-([\d]{2})-[.]*/g.exec(date)[1];
return matched;
};
also write someone else for mining year. And even an in_array function:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
Then you have to write a function that iterates your data and sum sum data of same months:
var format = (data) => {
var month_format = [0,0,0,0,0,0,0,0,0,0,0,0];
var last_format = [];
data.map(e => {
var year = dateToYear(e.date);
var years = last_format.map(data_e => data_e.name);
if (!inArray(year, years)) last_format.add({name: year, data: month_format});
var month = dateToMonth(e.date);
last_format.forEach(i => {
if (i.name === year) i[month - a] += e.data;
});
});
return last_format;
};

Write Array in nodeOpcua

Hiii, some body know how i can write Uint16Array in kepserver i got some error:
ConstantStatusCode {
_value: 2147483648,
_description: 'The value is bad but no specific reason is known.',
_name: 'Bad' } ]
i'm try this:
var valor = new Uint16Array([ 2, 23, 23, 12, 24, 3, 25, 3, 26, 3, 27, 3, 28, 1, 43690, 1, 1261, 0, 0, 0, 0, 0, 0, 0, 65535, 11 ])
nodeToWrite[0] = {
nodeId: resolveNodeId("ns=2;s=" + endereco[0].ADDRESS),
attributeId: opcua.AttributeIds.Value,
value: /new DataValue(/{ value: {/ Variant /
dataType: 5,
arrayType: 1,
value: valor,
}
}
}
const {AttributeIds, OPCUAClient, DataType, VariantArrayType} = require("node-opcua");
const endpointUrl = "opc.tcp://localhost:48010";
(async () => {
const client = OPCUAClient.create({ endpoint_must_exist: false});
await client.withSessionAsync(endpointUrl, async (session) => {
const arrayOfvalues = new Uint16Array([ 2, 23, 23, 12, 24, 3, 25, 3, 26, 3, 27, 3, 28, 1, 43690, 1, 1261, 0, 0, 0, 0, 0, 0, 0, 65535, 11 ]);
const nodeToWrite = {
nodeId: "ns=2;s=Demo.Static.Arrays.UInt16",
attributeId: AttributeIds.Value,
value: {
value: {
dataType: DataType.UInt16,
arrayType: VariantArrayType.Array,
value: arrayOfvalues,
}
}
}
const statusCode = await session.write(nodeToWrite);
console.log("write statusCode = ",statusCode.toString());
});
})();
As demonstrated above, writing a Array of Uint16 is ok when addressing node ns=2;s=Demo.Static.Arrays.UInt16 of UAServerCPP from Unified Automation.
I would contact Kepware for support.

MongoDB MapReduce weird bug

I'm trying this simple MapReduce operation:
function map() {
var gameDay = Math.floor((this.matchCreation - 1427846400000) / 86400000) + 1; // day of april 2015 when the game was played
this.teams.forEach (function (team){
**team.bans.forEach(function (ban){** // says bans is undefined
var value ={
banned : 1,
firstBanned: ( ((ban.pickTurn == 1) || (ban.pickTurn == 2))? 1 : 0 )
}
emit({championId: ban.championId,
day: Number(gameDay)}, value);
emit({championId: ban.championId,
day: "all"}, value);
});
});
}
function reduce(key, values) {
var a = values[0];
for(var i = 1 ; i<values.length ; i++){
var b = values[i]; // will merge 'b' into 'a'
a.banned += (b.banned? b.banned : 0);
a.firstBanned += (b.firstBanned? b.firstBanned : 0);
for (var attrname in b){
if(attrname != "banned" && attrname != "firstBanned")
a[attrname] = b[attrname];
}
}
return a;
}
matchesCollection.mapReduce(map, reduce, {
out: { reduce: "mapReduceResults" }
}, function (err, data){
if(err)
return callback (err);
callback (null, "OK");
});
It used to work before, but just when I tried to deploy the app after testing for a while, it seems to fail in this line: team.bans.forEach(function (ban){, says team.bans is undefined, although every one of the documents has a "teams" array and a "bans" array inside of each object in it, I even double checked it by querying the database and there is no document in which those fields dont exist.
So weird. The reduce function is a bit more complex but it seems to work alright, yet the map one (unlike Reduce, its supposed to be called just once per original document, right?) throws this unexplainable error. Could anyone give me some insight?
Sample input:
{
"_id": {
"$oid": "5531a63f2a3f135c11ed14a8"
},
"matchId": 1778704162,
"region": "NA",
"platformId": "NA1",
"matchMode": "CLASSIC",
"matchType": "MATCHED_GAME",
"matchCreation": 1427864425511,
"matchDuration": 1431,
"queueType": "URF_5x5",
"mapId": 11,
"season": "SEASON2015",
"matchVersion": "5.6.0.194",
"participants": [
{
"teamId": 100,
"spell1Id": 12,
"spell2Id": 4,
"championId": 81,
"highestAchievedSeasonTier": "SILVER",
"timeline": [],
"masteries": [],
"stats": {
"winner": false,
"champLevel": 19,
"item0": 1037,
"item1": 3078,
"item2": 3117,
"item3": 3035,
"item4": 3072,
"item5": 1038,
"item6": 3340,
"kills": 7,
"doubleKills": 1,
"tripleKills": 0,
"quadraKills": 0,
"pentaKills": 0,
"unrealKills": 0,
"largestKillingSpree": 3,
"deaths": 15,
"assists": 9,
"totalDamageDealt": 103191,
"totalDamageDealtToChampions": 22148,
"totalDamageTaken": 32924,
"largestCriticalStrike": 669,
"totalHeal": 2263,
"minionsKilled": 97,
"neutralMinionsKilled": 1,
"neutralMinionsKilledTeamJungle": 1,
"neutralMinionsKilledEnemyJungle": 0,
"goldEarned": 13923,
"goldSpent": 13273,
"combatPlayerScore": 0,
"objectivePlayerScore": 0,
"totalPlayerScore": 0,
"totalScoreRank": 0,
"magicDamageDealtToChampions": 6082,
"physicalDamageDealtToChampions": 15803,
"trueDamageDealtToChampions": 263,
"visionWardsBoughtInGame": 0,
"sightWardsBoughtInGame": 0,
"magicDamageDealt": 45997,
"physicalDamageDealt": 56651,
"trueDamageDealt": 543,
"magicDamageTaken": 25249,
"physicalDamageTaken": 7490,
"trueDamageTaken": 184,
"firstBloodKill": false,
"firstBloodAssist": false,
"firstTowerKill": false,
"firstTowerAssist": false,
"firstInhibitorKill": false,
"firstInhibitorAssist": false,
"inhibitorKills": 0,
"towerKills": 4,
"wardsPlaced": 2,
"wardsKilled": 0,
"largestMultiKill": 2,
"killingSprees": 1,
"totalUnitsHealed": 1,
"totalTimeCrowdControlDealt": 98
},
"participantId": 1,
"runes": []
},
... (9 more like that)
],
"participantIdentities": [],
"teams": [
{
"teamId": 100,
"winner": false,
"firstBlood": true,
"firstTower": false,
"firstInhibitor": true,
"firstBaron": false,
"firstDragon": true,
"towerKills": 6,
"inhibitorKills": 2,
"baronKills": 0,
"dragonKills": 3,
"vilemawKills": 0,
"dominionVictoryScore": 0,
"bans": [
{
"championId": 120,
"pickTurn": 1
},
{
"championId": 37,
"pickTurn": 3
},
{
"championId": 13,
"pickTurn": 5
}
]
},
{
"teamId": 200,
"winner": true,
"firstBlood": false,
"firstTower": true,
"firstInhibitor": false,
"firstBaron": false,
"firstDragon": false,
"towerKills": 11,
"inhibitorKills": 4,
"baronKills": 0,
"dragonKills": 0,
"vilemawKills": 0,
"dominionVictoryScore": 0,
"bans": [
{
"championId": 28,
"pickTurn": 2
},
{
"championId": 38,
"pickTurn": 4
},
{
"championId": 63,
"pickTurn": 6
}
]
}
]
}
Expected output:
{
_id: { championId: Number, day: Number }
value: { banned: Number, firstBanned: Number }
}
After that, its supposed to merge with the results of a previous MapReduce operation, copying all the fields of documents with the same key (in the reduce function), but thats irrelevant now since the error happens before...

Resources