How can I make a large if/else statement tighter? - javascript

I have something like the following:
if (value === section1) {
runChecks(checkObject[1].value1, checkObject[1].value2, leftAlign);
} else if (value === section2) {
runChecks(checkObject[2].value1, checkObject[2].value2, rightAlign);
} else if (value === section3) {
runChecks(checkObject[3].value1, checkObject[3].value2, leftAlign);
} else if (value === section4) {
runChecks(checkObject[4].value1, checkObject[4].value2, rightAlign);
} else if (value === section5) {
runChecks(checkObject[5].value1, checkObject[5].value2, leftAlign, true);
} else if (value === section6) {
runChecks(checkObject[6].value1, checkObject[6].value2, rightAlign);
} ...
It runs longer than this as there's a large number of pre-defined values.
Example of checkObject:
var checkObject = [{
value1: '19.1%',
value2: '19.1%',
}, {
value1: '19.1%',
value2: '19.1%',
}, {
value1: '19.1%',
value2: '19.1%',
}, ...
I want to break it down and make it more efficient but given there's variations on the data being passed to runChecks() I'm not sure how to manage it.

Use switch!
switch(value){
case section1:
runChecks(checkObject[1].value1, checkObject[1].value2, leftAlign);
break
case section2:
runChecks(checkObject[2].value1, checkObject[2].value2, rightAlign);
break
...
}
It's not really any shorter than using if / else if / else but it looks cleaner.

Actually, you can just use a for loop.
Create an array object containing all the sections. (I will provide the real javascript later. But here is some half-pseudocode).
var counter = 1;
var N = something;
var sectionArray = {section1, section2, section3, ..., sectionN};
for(;counter<N; counter++){
if(value === sectionArray[counter]){
runChecks(checkObject[counter].value1, checkObject[counter].value2, rightAlign);
break;
}
}

One way would be to use loop for instance.
let sections = ['section1', 'section2', 'section3', 'section4'];
for (let i = 0; i < sections.length; i++) {
if (value === sections[i]) {
runChecks(checkObject[1].value1, checkObject[1].value2, leftAlign);
}
}

You could use some with a short circuit if the value is found.
[section1, section2, section3, section4, section5, section6].some((v, i) => {
if (v === value) {
runChecks(
checkObject[i + 1].value1,
checkObject[i + 1].value2,
i % 2 ? rightAlign : leftAlign
i === 5 || undefined
);
return true;
}
});

Couldn't you iterate over the array? You might need to add all information that you require in the runChecks function though (I added mybool, since I wasn't sure where this true is coming from).
checkObject.forEach(function(value, index) {
let alignment = index % 2 == 0 ? leftAlign : rightAlign;
runChecks(value.value1, value.value2, alignment, value.mybool);
});

There are too many repeating parts in your code. I would do it this way.
var scs = [null, section1, section2, section3, section4, section5, section6];
var si = scs.indexOf(value);
var align = ((si&1)==1) ? leftAlign : rightAlign;
runChecks(checkObject[si].value1, checkObject[si].value2, align, si==5);

Related

localstorage variable only writes 0 to index.html

Hi when I run this block of code, the result of "clickamt" is 0 and it does not increment:
switch (isNaN(incremental) || isNaN(clickamt) || isnull(incremental) || isnull(clickamt) || isnull(curfloat) || isNaN(curfloat)) {
case true:
storage.setItem("clickamt", "0");
clickamt = (parseFloat(storage.getItem("clickamt")).toFixed(1));
storage.setItem("incremental", "1");
incremental = (parseInt(storage.getItem("incremental")));
storage.setItem("curfloat", "0");
curfloat = (parseFloat(storage.getItem("curfloat")).toFixed(1));
break;
case false:
if (clickamt % 1000 === curfloat) {
curfloat = (moneylevels()).toFixed(1);
}
clickamt = ((clickamt + incremental) + curfloat).toFixed(1);
incremental++;
storage.setItem("clickamt", (clickamt));
storage.setItem("incremental", (incremental).toString());
storage.setItem("curfloat", (curfloat).toString());
break;
}
The innerHTML of "clickamt" writes 0 and only 0 to "index.html".
I want "clickamt" of type float to increment by using incremental of type int plus curfloat which is of type float. "curfloat" is incremented by 0.1 per 1000 of "clickamt".
I don't think it's a parsing issue or anything of the sort. When I recoded it once it would just append the float it would increment by to the end of clickamt. This made me think there may be a parsing issue somewhere.
Some outputs I've seen are (0, 0.101011,00.010101,1,11,1111111,1111111111,etc.)
You can check on page load if the value for necessary key exists in localStorage. If the value is missing, then compute and save the new value. You can also have an extra event on which you can override the value of this key, but this will be a user action.
function computeRandomValue() {
var data = ["test", "test1", "test2", "test3", "test4"];
var index = Math.floor(Math.random() * 10) % data.length;
return data[index];
}
function setToLocalStorage(newVal) {
var lsKey = "_lsTest";
localStorage.setItem(lsKey, newVal);
}
function getFromLocalStorage() {
var lsKey = "_lsTest";
return localStorage.getItem(lsKey);
}
function initializePage() {
var _val = getFromLocalStorage();
if (!(_val && _val.trim().length > 0)) {
_val = computeAndSaveNewValue();
}
printValue(_val, "lblResult");
}
function computeAndSaveNewValue() {
var newVal = computeRandomValue();
setToLocalStorage(newVal);
printValue(newVal);
return newVal;
}
function printValue(value) {
var id = "lblResult";
document.getElementById(id).innerHTML = value;
}
(function() {
window.onload = initializePage;
})()

Check array elements and see if it contains flag my loops are not working

Trying to find out that if member of rxDetails contain combination inside rxInfos of flags based on that increment counter in below scenario it should retVlaue false because logic of for of loop should be at member level not the complete rxDetails object. what is implemented wrong any help ?
main.js
const rxDetails = [
{"member": 1 , "rxInfos":[
{ "firstFillIndicator": "Y",
"acceptDigitalFirstFill": "Y" },
{ "firstFillIndicator": "Y",
"acceptDigitalFirstFill": "Y" },
]},
{"member": 2 , "rxInfos":[
{ "firstFillIndicator": "N",
"acceptDigitalFirstFill": "Y" },
{ "firstFillIndicator": "N",
"acceptDigitalFirstFill": "Y" },
]},
]
function validateOrderRequest(rxDetails) {
let retVlaue = false;
let firstFillCounter = 0;
let refillCounter = 0;
for (const member of rxDetails) {
for (const rx of member.rxInfos) {
if (rx.firstFillIndicator === "Y" && rx.acceptDigitalFirstFill === "Y") {
firstFillCounter++;
} else {
refillCounter++;
}
}
if (refillCounter > 0 && firstFillCounter > 0) {
retVlaue = true;
return retVlaue;
} else {
retVlaue = false;
}
}
return retVlaue;
}
console.log(validateOrderRequest(rxDetails));
You want to return true if for any given element in the array, the element has:
At least one combination of "Y", "Y"
At least one other combination
Your problem is that your counter is running from the start to the end of the outer array. Instead, you should move the declarations inside the first for loop.
Alternatively, you can simplify this a bit by using the some array function for your loops.
validateOrderRequest(rxDetails) {
return rxDetails.some(member => {
let firstFillCounter = 0;
let refillCounter = 0;
for (let i = 0; i < member.rxInfos.length; i++) {
const rx = member.rxInfos[i];
if (rx.firstFillIndicator === "Y" &&
rx.acceptDigitalFirstFill === "Y") {
firstFillCounter++;
} else {
refillCounter++;
}
if (firstFillCounter > 0 && refillCounter > 0) {
return true;
}
}
return false;
});
}
some will return true for the first element it finds for the condition in the callback.
In this example, the inner loop returns true if a member has at least one "Y", "Y" combination and at least one !"Y", !"Y" combination.
The outer some returns true if at least one member satisfies this condition.
DEMO: https://stackblitz.com/edit/angular-read7t
The following part looks suspicious, why would you return upon meeting one condition and not the other? Remember returning stops the execution of the rest of the script
if (refillCounter > 0 && firstFillCounter > 0) {
retVlaue = true;
return retVlaue;
} else {
retVlaue = false;
}

Making a conditional function more efficient

I want to make a function that modifies a variable based on the given argument.
The function checks a variable and the number in that string. Then via the argument, I specify either increase or decrease the number by 1 (++1).
There is an array as well, that if the number is equal to the length of the array, then it turns to 1 and if the number is less than 1 then it is equal the size of the array. This is to make sure the number of the string does not get less than 1 or more than the length of the array.
the string with the number is Music1. So the circle would be like:
...., Music1, Music2, Music3, Music4, Music1, Music2, Music3, ....
var MyArray = ["Music1", "Music2", "Music3", "Music4"];
var currentMusic = "Music1";
$(".increase").on('click tap', nextMusic);
$(".decrease").on('click tap', previousMusic);
function nextMusic() {
unaryChange('plus')
}
function previousMusic() {
unaryChange('minus')
}
function unaryChange(operation) {
if (currentMusic === "Music4") {
currentMusic = "Music1"
} else if (currentMusic === "Music0") {
currentMusic = "Music4"
}
if (operation === "plus") {
currentMusic = currentMusic.replace(/\d+$/, function(n) {
return ++n
});
} else {
currentMusic = currentMusic.replace(/\d+$/, function(n) {
return --n
});
}
console.log(currentMusic);
$(".text").text(currentMusic);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="increase">increase</button>
<button class="decrease">decrease</button>
<p class="text">value</p>
The above method almost does the job, however I am looking for an easier and more professional solution. It does not look efficient. For example, there must be a better way to specify the argument operation instead of a string like plus, or the conditions.
I need this function to be rewritten in a better way, more professionally and works as described.
Thanks in advance.
It is better to work with array index instead of the values
function unaryChange(operation) {
var currentIndex = MyArray.findIndex(function(item) {
return item === currentMusic;
});
if(operation === 'plus') {
newIndex = currentIndex < MyArray.length - 1 && currentIndex + 1 || 0;
} else {
newIndex = currentIndex > 0 ? currentIndex -1 : MyArray.length -1;
}
currentMusic = MyArray[newIndex]
$(".text").text(currentMusic);
}
In this case whatever the size of the array it will work.
A working example https://jsbin.com/rahomorupa/4/edit?html,js,console,output
Building on Joe's answer I'd suggest you define constants for plus and minus as +1 and -1 respectively to simplify the increment/decrement logic, along with the modulus operator to handle the array wrap-around:
const PLUS = 1;
const MINUS = -1;
function unaryChange(operation) {
var currentIndex = MyArray.findIndex(function(item) {
return item === currentMusic;
});
// If it's invoked as unaryChange(PLUS) or unaryChange(MINUS)
// we don't need any conditional logic to handle the increment,
// and with the % operator we don't need additional bounds overflow
// logic. (This latter bit is complicated somewhat by the need to
// handle a minus step from index 0.)
const {length} = MyArray;
const newIndex = ((currentIndex + operation) % length + length) % length;
currentMusic = MyArray[newIndex]
$(".text").text(currentMusic);
}
The % operator returns the remainder of a division, which conveniently loops back around to 0 when used with an array index against the array length:
const array = ['first', 'second', 'third'];
for (let i = 0; i < 20; i++) {
console.log(array[i % array.length]);
}
You can pass a Boolean for plus, use an arrow function, and a ternary operator:
var MyArray = ["Music1", "Music2", "Music3", "Music4"];
var currentMusic = "Music1";
$(".increase").on('click tap', nextMusic);
$(".decrease").on('click tap', previousMusic);
function nextMusic() {
unaryChange(true)
}
function previousMusic() {
unaryChange(false)
}
function unaryChange(plus) {
currentMusic = currentMusic == "Music4" ? "Music1" : (currentMusic == "Music0" ? "Music4" : currentMusic);
currentMusic = currentMusic.replace(/\d+$/, n => plus ? ++n : --n);
console.log(currentMusic);
$(".text").text(currentMusic);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="increase">increase</button>
<button class="decrease">decrease</button>
<p class="text">value</p>
Since you have an array of music, it's better to use that instead. There's no need to operate from the text, you just need to update the array index to the next value and pass it to the function, and let it get the song name directly.
Since we want to be between the boundaries of 0 and the array length, here's what is used to do this:
Get the next song: (currentTrackIndex + 1) % tracks.length. That will get the next index value and apply modulo to it so it will round back if it exceedes the array length.
Get the previous song: (currentTrackIndex - 1 + tracks.length) % tracks.length. It's pretty much the same as getting the next song, save for the case when the index it's already at zero. If you apply modulo to a negative number, you will get a negative result and will mess up your array index. So instead of using a conditional clause ("if (currentTrackIndex === 0 ...)"), let's add the array length. Why? Because since 0 % n == 0 and n % n == 0, adding the array length will not change the modulo result, while keeping your index as a positive number.
(I changed the name from MyArray to tracks and unaryChange to changeTrack, to give it better meaning clarity)
var tracks = ["Music1", "Music2", "Music3", "Music4"];
var currentTrackIndex = 0;
$(".increase").on('click tap', nextMusic);
$(".decrease").on('click tap', previousMusic);
function nextMusic() {
//It will move to the next track. If it's over the array length, it will reset to 0
changeTrack((currentTrackIndex + 1) % tracks.length)
}
function previousMusic() {
//It will move to the previous song. If it's below zero, it will reset to the last track index
changeTrack((currentTrackIndex + tracks.length - 1) % tracks.length)
}
function changeTrack(newTrackIndex) {
currentTrackIndex = newTrackIndex;
var currentTrack = tracks[currentTrackIndex];
console.log(currentTrackIndex);
$(".text").text(currentTrack);
}
Here's how I'd do it. Since it seems that the word Music is just a prefix used to designate a particular unit, I wont store it over and over again in a array.
As for jQuery? Yeah, nah.
"use strict";
function byId(id){return document.getElementById(id)}
window.addEventListener('load', onLoaded, false);
function onLoaded(evt)
{
let prefix = 'Music';
let count = 4, index=0;
byId('increase').addEventListener('click', function(evt){index++; index %= count; update();}, false);
byId('decrease').addEventListener('click', function(evt){index--; if (index<0) index=count-1; update();}, false);
function update()
{
byId('status').textContent = `${prefix}${index+1}`;
}
}
<span id='status'>Music1</span><br>
<button id='increase'>+</button><button id='decrease'>-</button>
I think this is a good start. Accessing the indices of the array versus the values feels a lot cleaner. Using ternaries cleans up a lot of logic into one line as well.
var MyArray = ["Music1", "Music2", "Music3", "Music4"];
var currentMusic = 0;
$(".increase").on('click tap', unaryChange);
$(".decrease").on('click tap', unaryChange);
function unaryChange() {
if (event.target.className === "increase") {
currentMusic = (currentMusic < 3 ? currentMusic + 1 : 0)
} else {
currentMusic = (currentMusic > 0 ? currentMusic -= 1 : 3)
}
console.log(MyArray[currentMusic]);
$(".text").text(MyArray[currentMusic]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="increase">increase</button>
<button class="decrease">decrease</button>
<p class="text">value</p>

What is the size of objects in JavaScript? [duplicate]

I want to know the size occupied by a JavaScript object.
Take the following function:
function Marks(){
this.maxMarks = 100;
}
function Student(){
this.firstName = "firstName";
this.lastName = "lastName";
this.marks = new Marks();
}
Now I instantiate the student:
var stud = new Student();
so that I can do stuff like
stud.firstName = "new Firstname";
alert(stud.firstName);
stud.marks.maxMarks = 200;
etc.
Now, the stud object will occupy some size in memory. It has some data and more objects.
How do I find out how much memory the stud object occupies? Something like a sizeof() in JavaScript? It would be really awesome if I could find it out in a single function call like sizeof(stud).
I’ve been searching the Internet for months—couldn’t find it (asked in a couple of forums—no replies).
I have re-factored the code in my original answer. I have removed the recursion and removed the assumed existence overhead.
function roughSizeOfObject( object ) {
var objectList = [];
var stack = [ object ];
var bytes = 0;
while ( stack.length ) {
var value = stack.pop();
if ( typeof value === 'boolean' ) {
bytes += 4;
}
else if ( typeof value === 'string' ) {
bytes += value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes += 8;
}
else if
(
typeof value === 'object'
&& objectList.indexOf( value ) === -1
)
{
objectList.push( value );
for( var i in value ) {
stack.push( value[ i ] );
}
}
}
return bytes;
}
The Google Chrome Heap Profiler allows you to inspect object memory use.
You need to be able to locate the object in the trace which can be tricky. If you pin the object to the Window global, it is pretty easy to find from the "Containment" listing mode.
In the attached screenshot, I created an object called "testObj" on the window. I then located in the profiler (after making a recording) and it shows the full size of the object and everything in it under "retained size".
More details on the memory breakdowns.
In the above screenshot, the object shows a retained size of 60. I believe the unit is bytes here.
Sometimes I use this to flag really big objects that might be going to the client from the server. It doesn't represent the in memory footprint. It just gets you approximately what it'd cost to send it, or store it.
Also note, it's slow, dev only. But for getting an ballpark answer with one line of code it's been useful for me.
roughObjSize = JSON.stringify(bigObject).length;
I just wrote this to solve a similar (ish) problem. It doesn't exactly do what you may be looking for, ie it doesn't take into account how the interpreter stores the object.
But, if you are using V8, it should give you a fairly ok approximation as the awesome prototyping and hidden classes lick up most of the overhead.
function roughSizeOfObject( object ) {
var objectList = [];
var recurse = function( value )
{
var bytes = 0;
if ( typeof value === 'boolean' ) {
bytes = 4;
}
else if ( typeof value === 'string' ) {
bytes = value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes = 8;
}
else if
(
typeof value === 'object'
&& objectList.indexOf( value ) === -1
)
{
objectList[ objectList.length ] = value;
for( i in value ) {
bytes+= 8; // an assumed existence overhead
bytes+= recurse( value[i] )
}
}
return bytes;
}
return recurse( object );
}
Here's a slightly more compact solution to the problem:
const typeSizes = {
"undefined": () => 0,
"boolean": () => 4,
"number": () => 8,
"string": item => 2 * item.length,
"object": item => !item ? 0 : Object
.keys(item)
.reduce((total, key) => sizeOf(key) + sizeOf(item[key]) + total, 0)
};
const sizeOf = value => typeSizes[typeof value](value);
There is a NPM module to get object sizeof, you can install it with npm install object-sizeof
var sizeof = require('object-sizeof');
// 2B per character, 6 chars total => 12B
console.log(sizeof({abc: 'def'}));
// 8B for Number => 8B
console.log(sizeof(12345));
var param = {
'a': 1,
'b': 2,
'c': {
'd': 4
}
};
// 4 one two-bytes char strings and 3 eighth-bytes numbers => 32B
console.log(sizeof(param));
This is a hacky method, but i tried it twice with different numbers and it seems to be consistent.
What you can do is to try and allocate a huge number of objects, like one or two million objects of the kind you want. Put the objects in an array to prevent the garbage collector from releasing them (note that this will add a slight memory overhead because of the array, but i hope this shouldn't matter and besides if you are going to worry about objects being in memory, you store them somewhere). Add an alert before and after the allocation and in each alert check how much memory the Firefox process is taking. Before you open the page with the test, make sure you have a fresh Firefox instance. Open the page, note the memory usage after the "before" alert is shown. Close the alert, wait for the memory to be allocated. Subtract the new memory from the older and divide it by the amount of allocations. Example:
function Marks()
{
this.maxMarks = 100;
}
function Student()
{
this.firstName = "firstName";
this.lastName = "lastName";
this.marks = new Marks();
}
var manyObjects = new Array();
alert('before');
for (var i=0; i<2000000; i++)
manyObjects[i] = new Student();
alert('after');
I tried this in my computer and the process had 48352K of memory when the "before" alert was shown. After the allocation, Firefox had 440236K of memory. For 2million allocations, this is about 200 bytes for each object.
I tried it again with 1million allocations and the result was similar: 196 bytes per object (i suppose the extra data in 2mill was used for Array).
So, here is a hacky method that might help you. JavaScript doesn't provide a "sizeof" method for a reason: each JavaScript implementaion is different. In Google Chrome for example the same page uses about 66 bytes for each object (judging from the task manager at least).
Having the same problem. I searched on Google and I want to share with stackoverflow community this solution.
Important:
I used the function shared by Yan Qing on github
https://gist.github.com/zensh/4975495
function memorySizeOf(obj) {
var bytes = 0;
function sizeOf(obj) {
if(obj !== null && obj !== undefined) {
switch(typeof obj) {
case 'number':
bytes += 8;
break;
case 'string':
bytes += obj.length * 2;
break;
case 'boolean':
bytes += 4;
break;
case 'object':
var objClass = Object.prototype.toString.call(obj).slice(8, -1);
if(objClass === 'Object' || objClass === 'Array') {
for(var key in obj) {
if(!obj.hasOwnProperty(key)) continue;
sizeOf(obj[key]);
}
} else bytes += obj.toString().length * 2;
break;
}
}
return bytes;
};
function formatByteSize(bytes) {
if(bytes < 1024) return bytes + " bytes";
else if(bytes < 1048576) return(bytes / 1024).toFixed(3) + " KiB";
else if(bytes < 1073741824) return(bytes / 1048576).toFixed(3) + " MiB";
else return(bytes / 1073741824).toFixed(3) + " GiB";
};
return formatByteSize(sizeOf(obj));
};
var sizeOfStudentObject = memorySizeOf({Student: {firstName: 'firstName', lastName: 'lastName', marks: 10}});
console.log(sizeOfStudentObject);
What do you think about it?
Sorry I could not comment, so I just continue the work from tomwrong.
This enhanced version will not count object more than once, thus no infinite loop.
Plus, I reckon the key of an object should be also counted, roughly.
function roughSizeOfObject( value, level ) {
if(level == undefined) level = 0;
var bytes = 0;
if ( typeof value === 'boolean' ) {
bytes = 4;
}
else if ( typeof value === 'string' ) {
bytes = value.length * 2;
}
else if ( typeof value === 'number' ) {
bytes = 8;
}
else if ( typeof value === 'object' ) {
if(value['__visited__']) return 0;
value['__visited__'] = 1;
for( i in value ) {
bytes += i.length * 2;
bytes+= 8; // an assumed existence overhead
bytes+= roughSizeOfObject( value[i], 1 )
}
}
if(level == 0){
clear__visited__(value);
}
return bytes;
}
function clear__visited__(value){
if(typeof value == 'object'){
delete value['__visited__'];
for(var i in value){
clear__visited__(value[i]);
}
}
}
roughSizeOfObject(a);
i want to know if my memory reduction efforts actually help in reducing memory
Following up on this comment, here's what you should do:
Try to produce a memory problem - Write code that creates all these objects and graudally increase the upper limit until you ran into a problem (Browser crash, Browser freeze or an Out-Of-memory error). Ideally you should repeat this experiment with different browsers and different operating system.
Now there are two options:
option 1 - You didn't succeed in producing the memory problem. Hence, you are worrying for nothing. You don't have a memory issue and your program is fine.
option 2- you did get a memory problem. Now ask yourself whether the limit at which the problem occurred is reasonable (in other words: is it likely that this amount of objects will be created at normal use of your code). If the answer is 'No' then you're fine. Otherwise you now know how many objects your code can create. Rework the algorithm such that it does not breach this limit.
This Javascript library sizeof.js does the same thing.
Include it like this
<script type="text/javascript" src="sizeof.js"></script>
The sizeof function takes an object as a parameter and returns its approximate size in bytes. For example:
// define an object
var object =
{
'boolean' : true,
'number' : 1,
'string' : 'a',
'array' : [1, 2, 3]
};
// determine the size of the object
var size = sizeof(object);
The sizeof function can handle objects that contain multiple references to other objects and recursive references.
Originally published here.
If your main concern is the memory usage of your Firefox extension, I suggest checking with Mozilla developers.
Mozilla provides on its wiki a list of tools to analyze memory leaks.
Chrome developer tools has this functionality. I found this article very helpful and does exactly what you want:
https://developers.google.com/chrome-developer-tools/docs/heap-profiling
Many thanks to everyone that has been working on code for this!
I just wanted to add that I've been looking for exactly the same thing, but in my case it's for managing a cache of processed objects to avoid having to re-parse and process objects from ajax calls that may or may not have been cached by the browser. This is especially useful for objects that require a lot of processing, usually anything that isn't in JSON format, but it can get very costly to keep these things cached in a large project or an app/extension that is left running for a long time.
Anyway, I use it for something something like:
var myCache = {
cache: {},
order: [],
size: 0,
maxSize: 2 * 1024 * 1024, // 2mb
add: function(key, object) {
// Otherwise add new object
var size = this.getObjectSize(object);
if (size > this.maxSize) return; // Can't store this object
var total = this.size + size;
// Check for existing entry, as replacing it will free up space
if (typeof(this.cache[key]) !== 'undefined') {
for (var i = 0; i < this.order.length; ++i) {
var entry = this.order[i];
if (entry.key === key) {
total -= entry.size;
this.order.splice(i, 1);
break;
}
}
}
while (total > this.maxSize) {
var entry = this.order.shift();
delete this.cache[entry.key];
total -= entry.size;
}
this.cache[key] = object;
this.order.push({ size: size, key: key });
this.size = total;
},
get: function(key) {
var value = this.cache[key];
if (typeof(value) !== 'undefined') { // Return this key for longer
for (var i = 0; i < this.order.length; ++i) {
var entry = this.order[i];
if (entry.key === key) {
this.order.splice(i, 1);
this.order.push(entry);
break;
}
}
}
return value;
},
getObjectSize: function(object) {
// Code from above estimating functions
},
};
It's a simplistic example and may have some errors, but it gives the idea, as you can use it to hold onto static objects (contents won't change) with some degree of intelligence. This can significantly cut down on any expensive processing requirements that the object had to be produced in the first place.
The accepted answer does not work with Map, Set, WeakMap and other iterable objects. (The package object-sizeof, mentioned in other answer, has the same problem).
Here's my fix
export function roughSizeOfObject(object) {
const objectList = [];
const stack = [object];
const bytes = [0];
while (stack.length) {
const value = stack.pop();
if (value == null) bytes[0] += 4;
else if (typeof value === 'boolean') bytes[0] += 4;
else if (typeof value === 'string') bytes[0] += value.length * 2;
else if (typeof value === 'number') bytes[0] += 8;
else if (typeof value === 'object' && objectList.indexOf(value) === -1) {
objectList.push(value);
if (typeof value.byteLength === 'number') bytes[0] += value.byteLength;
else if (value[Symbol.iterator]) {
// eslint-disable-next-line no-restricted-syntax
for (const v of value) stack.push(v);
} else {
Object.keys(value).forEach(k => {
bytes[0] += k.length * 2; stack.push(value[k]);
});
}
}
}
return bytes[0];
}
It also includes some other minor improvements: counts keys storage and works with ArrayBuffer.
function sizeOf(parent_data, size)
{
for (var prop in parent_data)
{
let value = parent_data[prop];
if (typeof value === 'boolean')
{
size += 4;
}
else if (typeof value === 'string')
{
size += value.length * 2;
}
else if (typeof value === 'number')
{
size += 8;
}
else
{
let oldSize = size;
size += sizeOf(value, oldSize) - oldSize;
}
}
return size;
}
function roughSizeOfObject(object)
{
let size = 0;
for each (let prop in object)
{
size += sizeOf(prop, 0);
} // for..
return size;
}
I use Chrome dev tools' Timeline tab, instantiate increasingly large amounts of objects, and get good estimates like that. You can use html like this one below, as boilerplate, and modify it to better simulate the characteristics of your objects (number and types of properties, etc...). You may want to click the trash bit icon at the bottom of that dev tools tab, before and after a run.
<html>
<script>
var size = 1000*100
window.onload = function() {
document.getElementById("quantifier").value = size
}
function scaffold()
{
console.log("processing Scaffold...");
a = new Array
}
function start()
{
size = document.getElementById("quantifier").value
console.log("Starting... quantifier is " + size);
console.log("starting test")
for (i=0; i<size; i++){
a[i]={"some" : "thing"}
}
console.log("done...")
}
function tearDown()
{
console.log("processing teardown");
a.length=0
}
</script>
<body>
<span style="color:green;">Quantifier:</span>
<input id="quantifier" style="color:green;" type="text"></input>
<button onclick="scaffold()">Scaffold</button>
<button onclick="start()">Start</button>
<button onclick="tearDown()">Clean</button>
<br/>
</body>
</html>
Instantiating 2 million objects of just one property each (as in this code above) leads to a rough calculation of 50 bytes per object, on my Chromium, right now. Changing the code to create a random string per object adds some 30 bytes per object, etc.
Hope this helps.
If you need to programatically check for aprox. size of objects you can also check this library http://code.stephenmorley.org/javascript/finding-the-memory-usage-of-objects/ that I have been able to use for objects size.
Otherwise I suggest to use the Chrome/Firefox Heap Profiler.
I had problems with the above answer with an ArrayBuffer.
After checking the documentation, I found that ArrayBuffer has a byteLength property which tells me exactly what I need, hence:
function sizeOf(data)
{
if (typeof(data) === 'object')
{
if (data instanceof ArrayBuffer)
{
return data.byteLength;
}
// other objects goes here
}
// non-object cases goes here
}
console.log(sizeOf(new ArrayBuffer(15))); // 15
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/byteLength
Building upon the already compact solution from #Dan, here's a self-contained function version of it. Variable names are reduced to single letters for those who just want it to be as compact as possible at the expense of context.
const ns = {};
ns.sizeof = function(v) {
let f = ns.sizeof, //this needs to match the name of the function itself, since arguments.callee.name is defunct
o = {
"undefined": () => 0,
"boolean": () => 4,
"number": () => 8,
"string": i => 2 * i.length,
"object": i => !i ? 0 : Object
.keys(i)
.reduce((t, k) => f(k) + f(i[k]) + t, 0)
};
return o[typeof v](v);
};
ns.undef;
ns.bool = true;
ns.num = 1;
ns.string = "Hello";
ns.obj = {
first_name: 'John',
last_name: 'Doe',
born: new Date(1980, 1, 1),
favorite_foods: ['Pizza', 'Salad', 'Indian', 'Sushi'],
can_juggle: true
};
console.log(ns.sizeof(ns.undef));
console.log(ns.sizeof(ns.bool));
console.log(ns.sizeof(ns.num));
console.log(ns.sizeof(ns.string));
console.log(ns.sizeof(ns.obj));
console.log(ns.sizeof(ns.obj.favorite_foods));
I believe you forgot to include 'array'.
typeOf : function(value) {
var s = typeof value;
if (s === 'object')
{
if (value)
{
if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length')) && typeof value.splice === 'function')
{
s = 'array';
}
}
else
{
s = 'null';
}
}
return s;
},
estimateSizeOfObject: function(value, level)
{
if(undefined === level)
level = 0;
var bytes = 0;
if ('boolean' === typeOf(value))
bytes = 4;
else if ('string' === typeOf(value))
bytes = value.length * 2;
else if ('number' === typeOf(value))
bytes = 8;
else if ('object' === typeOf(value) || 'array' === typeOf(value))
{
for(var i in value)
{
bytes += i.length * 2;
bytes+= 8; // an assumed existence overhead
bytes+= estimateSizeOfObject(value[i], 1)
}
}
return bytes;
},
formatByteSize : function(bytes)
{
if (bytes < 1024)
return bytes + " bytes";
else
{
var floatNum = bytes/1024;
return floatNum.toFixed(2) + " kb";
}
},
I know this is absolutely not the right way to do it, yet it've helped me a few times in the past to get the approx object file size:
Write your object/response to the console or a new tab, copy the results to a new notepad file, save it, and check the file size. The notepad file itself is just a few bytes, so you'll get a fairly accurate object file size.

excluding "missing" values in reductio.avg()

I was hoping to use reductio to compute averages within my crossfilter groups. My dataset includes missing values (represented by null) that I'd like to exclude when calculating the average. However, I don't see a way to tell reductio to exclude certain values, and it treats the null values as 0.
I wrote a custom reduce function to accomplish this without using reductio:
function reduceAvg(attr) {
return {
init: function() {
return {
count: 0,
sum: 0,
avg: 0
};
},
add: function(reduction, record) {
if (record[attr] !== null) {
reduction.count += 1;
reduction.sum += record[attr];
if (reduction.count > 0) {
reduction.avg = reduction.sum / reduction.count;
}
else {
reduction.avg = 0;
}
}
return reduction;
},
remove: function(reduction, record) {
if (record[attr] !== null) {
reduction.count -= 1;
reduction.sum -= record[attr];
if (reduction.count > 0) {
reduction.avg = reduction.sum / reduction.count;
}
else {
reduction.avg = 0;
}
}
return reduction;
}
};
}
Is there a way to do this using reductio? Maybe using exception aggregation? I haven't fully wrapped my head around how exceptions work in reductio.
I think you should be able to average over 'myAttr' excluding null and undefined by doing:
reductio()
.filter(function(d) { return d[myAttr] !== null && d[myAttr] !== undefined; })
.avg(function(d) { return d[myAttr]; });
If that doesn't work as expected, please file an issue as it is a bug.

Categories

Resources