I have JavaScript Object say:
var a = {b: Infinity, c: 10};
When I do
var b = JSON.stringify(a);
it returns the following
b = "{"b":null, "c":10}";
How is the JSON.stringify converts the object to strings?
I tried MDN Solution.
function censor(key, value) {
if (value == Infinity) {
return "Infinity";
}
return value;
}
var b = JSON.stringify(a, censor);
But in this case I have to return the string "Infinity" not Infinity. If I return Infinity it again converts Infinity to null.
How do I solve this problem.
Like the other answers stated, Infinity is not part of the values JSON can store as value.
You can reverse the censor method on parsing the JSON:
var c = JSON.parse(b, function (key, value) {
return value === "Infinity" ? Infinity : value;
});
JSON doesn't have Infinity or NaN, see this question:
JSON left out Infinity and NaN; JSON status in ECMAScript?
Hence { b: Infinity, c: 10 } isn't valid JSON. If you need to encode infinity in JSON, you probably have to resort to objects:
{
"b": { "is_infinity": true, "value": null },
"c": { "is_infinity": false, "value": 10 }
}
This structure is generated by, given your above example does what you say it does,
function censor(key, value) {
if (value == Infinity) {
return JSON.stringify ( { is_infinity: true, value: null } );
} else {
return JSON.stringify ( { is_infinity: false, value: value } );
}
}
var b = JSON.stringify(a, censor);
JSON doesn't support infinity/Nan.
Please refer the below links.
http://www.markhansen.co.nz/inspecting-with-json-stringify/
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
JSON left out Infinity and NaN; JSON status in ECMAScript?
Thanks,
Siva
Related
I have the following method that I need to test:
public async Task<SomeClass> GetAsync(string partitionKey, string rowKey)
{
var entities = new List<SomeClass>();
await foreach (var e in _tableClient.QueryAsync<SomeClass>(x => x.PartitionKey == partitionKey && x.RowKey == rowKey))
{
entities.Add(e);
}
return entities.FirstOrDefault();
}
I'd like to setup the _tableClient.QueryAsync() (in the moq) to be able to return different result based on the input parameter. This is important to ensure my unit test covers the logic.
My attempt is:
var thingsToMock = new List<(string PartitionKey, string RowKey, string Value)>() {
("maxCount", "maxCount", "0"),
("maxCount", "xyz", "1000"),
("maxCount", "abc", "2000")
};
var tableClientMock = new Mock<TableClient>();
foreach (var thingToMock in thingsToMock)
{
var returnPage = Page<SomeClass>.FromValues(new List<SomeClass>
{
new SomeClass{ PartitionKey = thingToMock.PartitionKey, RowKey = thingToMock.RowKey, Value = thingToMock.Value }
}, null, new Mock<Response>().Object);
var returnPages = AsyncPageable<SomeClass>.FromPages(new[] { returnPage });
Expression<Func<SomeClass, bool>> exp = (x) => x.PartitionKey == thingToMock.PartitionKey && x.RowKey == thingToMock.RowKey ? true : false;
tableClientMock
.Setup(i => i.QueryAsync<SomeClass>(It.Is<Expression<Func<SomeClass, bool>>>(expression => LambdaExpression.Equals(expression, exp)), null, null, default))
.Returns(returnPages);
}
The issue is that the _tableClientMock doesn't seem to return what I expected when I call GetAsync("maxCount", "abc"). I'd expect with this call, it would pass in the same parameters to tableClient.QueryAsync() method, which in my Mock should return instance of SomeClass with value of 2000. But instead, it throw "Object reference not set to an instance of an object." error.
If I change the tableClientMock setup for QueryAsync to be the following, it somewhat works:
.Setup(i => i.QueryAsync<SomeClass>(It.IsAny<Expression<Func<SomeClass, bool>>>(), null, null, default))
But this will not achieve my objective, which is to be able to pass different parameters (partitionKey and rowKey) to get different result.
I'm using the following NuGet package:
"Azure.Data.Tables" Version="12.7.1"
"moq" Version="4.14.1"
I am trying to achieve a small amount of javascript code that is able to locate a key that contains another key with the most array element occurrences in a string. It's a little hard to explain but I have given an example below. I have tried several filters, finds, and lengthy code loops with no luck. Anything would help, thanks :)
const object = {
keyone: {
tags: ["game","video","tv","playstation"]
},
keytwo: {
tags: ["book", "sport", "camping", "out"]
}
};
const string = "This is an example, out playstaion, tv and video games are cool!";
// I am trying to locate the key that contains the most tags in a string.
// In this case the result I am looking for would be "keytwo",
// because it's tags have greater occurances inside the string (playstaion, tv, video, game/s).
This should do it, though you might want to consider adding keyword stemming.
const object = {
keyone: {
tags: ["game", "video", "tv", "playstation"]
},
keytwo: {
tags: ["book", "sport", "camping", "out"]
}
};
const string = "This is an example, out playstaion, tv and video games are cool!";
result = {}
for (const [key, value] of Object.entries(object)) {
result[key] = value.tags.reduce((acc, item) => (acc += (string.match(item) || []).length), 0)
}
console.log(result)
Result:
{ keyone: 3, keytwo: 1 }
Edit:
How to count:
let result_key;
let result_count = 0;
for (const [key, value] of Object.entries(object)) {
const result = value.tags.reduce((acc, item) => (acc += (string.match(item) || []).length), 0);
if(result > result_count) {
result_count = result;
result_key = key;
}
}
console.log(result_key, result_count)
Result:
keyone 3
I have a document list that consists of:
time
sessionId
appv
museum
I would like to use the couchDB map/reduce function to get the result:
key : sessionId, value : {begin : time, end: time, appv : appv, museum : museum}
for the begin value: the minimum time value.
for the end value: the maximum time value
Currently I can have the minimum and maximum value with this code:
MAP :
function(doc) {
if(doc.sessionId) {
emit(doc.sessionId, [doc.time])
}
}
REDUCE :
function(keys, values, rereduce) {
if (rereduce) {
return {
'min': values.reduce(function(a, b) { return Math.min(a, b.min) }, Infinity),
'max': values.reduce(function(a, b) { return Math.max(a, b.max) }, -Infinity),
}
} else {
return {
'min': Math.min.apply(null, values),
'max': Math.max.apply(null, values),
}
}
}
RESULT :
{"rows":[
{"key":"fromDev1548326238156","value":{"min":2,"max":999}}
]}
And when I use this map function:
function(doc) {
if(doc.sessionId) {
emit(doc.sessionId, [doc.time, doc.museum, doc.appv])
}
}
I can't find the reduce function that allows me to get the result I want
Can you help me?
I have a geojson file which I'm getting from this website which somehow contains corrupt data, with a coordinate value = null.
http://measuringamsterdam.nl/datalist/kijk/
And I'm using it in my code like this:
//Retrieve all data and add to map
$.each(datalistObject['idlist'], function(key, value) {
$.getJSON('http://measuringamsterdam.nl/datalist/kijk/' + value['id'], function(data) {
textbox = value['name'];
var dataid = L.geoJson([data], {
style: function (feature) {
return feature.properties && feature.properties.style;
},
onEachFeature: onEachFeature,
pointToLayer: function (feature, latlng) {
return L.marker(latlng, {
icon: value['icon']
});
}
}).addTo(jsonGroup);
console.log(jsonGroup);
},function(xhr) { console.error(xhr); });
});
Now somehow I need to filter out the features/objects where the coordinates have a null value.
I really need to filter the data that point in my code since I need the + value['id'] part in the getJSON code.
Ane ideas?
Using the following code you will generate a new array. Which will include only the filtered data.
var newArray = data.filter(function (el) {
return el.value != 'null';
});
You can also apply multiple filters, for example:
return el.value_a != 'null' && el.value_b > 100;
Hopefully this will work!
I have a collection of events that look like
{
_id: BSONID
name: "event_name",
values: {a: 10, b: 1000, c: 50}
}
I'm trying to use mapReduce them using
map = function() {
return emit([this.name, this.values['a']], this.values['b']);
}
reduce = function(key, values) {
// stuff
}
collection.mapReduce(map, reduce, { out: { inline: 1 } }, callback);
However, I would like to be able to dynamically change which values I map against. In essence, I'd like to have
var key = 'a';
var value = 'b';
map = function ()
{
return emit([this.name, this.values[key]], this.values[value]);
}
The problem is that the execution context isn't passed to mongodb. Any solution that doesn't rely on using string for functions?
Yes, you can pass a "scope" variable to MapReduce:
scope = {key : "a", value : "b"};
collection.mapReduce(map, reduce, {scope : scope, out: { inline: 1 } }, callback);