javascript: Alter the output of a function to the specified decimal place - javascript

I am not very good with my javascript but recently needed to work with a library to output an aggregated table. Was using fin-hypergrid.
There was a part where I need to insert a sum function (rollups.sum(11) in this example)to an object so that it can compute an aggregated value in a table like so:
aggregates = {Value: rollups.sum(11)}
I would like to change this value to return 2 decimal places and tried:
rollups.sum(11).toFixed(2)
However, it gives the error : "rollups.sum(...).toFixed is not a function"
If I try something like:
parseFloat(rollups.sum(11)).toFixed(2)
it throws the error: "can't assign to properties of (new String("NaN")): not an object"
so it has to be a function object.
May I know if there is a way to alter the function rollups.sum(11) to return a function object with 2 decimal places?
(side info: rollups.sum(11) comes from a module which gives:
sum: function(columnIndex) {
return sum.bind(this, columnIndex);
}
)
Sorry I could not post sample output here due to data confidentiality issues.
However, here is the code from the example I follow. I basically need to change rollups.whatever to give decimal places. The "11" in sum(11) here refers to a "column index".
window.onload = function() {
var Hypergrid = fin.Hypergrid;
var drillDown = Hypergrid.drillDown;
var TreeView = Hypergrid.TreeView;
var GroupView = Hypergrid.GroupView;
var AggView = Hypergrid.AggregationsView;
// List of properties to show as checkboxes in this demo's "dashboard"
var toggleProps = [{
label: 'Grouping',
ctrls: [
{ name: 'treeview', checked: false, setter: toggleTreeview },
{ name: 'aggregates', checked: false, setter: toggleAggregates },
{ name: 'grouping', checked: false, setter: toggleGrouping}
]
}
];
function derivedPeopleSchema(columns) {
// create a hierarchical schema organized by alias
var factory = new Hypergrid.ColumnSchemaFactory(columns);
factory.organize(/^(one|two|three|four|five|six|seven|eight)/i, { key: 'alias' });
var columnSchema = factory.lookup('last_name');
if (columnSchema) {
columnSchema.defaultOp = 'IN';
}
//factory.lookup('birthState').opMenu = ['>', '<'];
return factory.schema;
}
var customSchema = [
{ name: 'last_name', type: 'number', opMenu: ['=', '<', '>'], opMustBeInMenu: true },
{ name: 'total_number_of_pets_owned', type: 'number' },
{ name: 'height', type: 'number' },
'birthDate',
'birthState',
'employed',
{ name: 'income', type: 'number' },
{ name: 'travel', type: 'number' }
];
var peopleSchema = customSchema; // or try setting to derivedPeopleSchema
var gridOptions = {
data: people1,
schema: peopleSchema,
margin: { bottom: '17px' }
},
grid = window.g = new Hypergrid('div#json-example', gridOptions),
behavior = window.b = grid.behavior,
dataModel = window.m = behavior.dataModel,
idx = behavior.columnEnum;
console.log('Fields:'); console.dir(behavior.dataModel.getFields());
console.log('Headers:'); console.dir(behavior.dataModel.getHeaders());
console.log('Indexes:'); console.dir(idx);
var treeView, dataset;
function setData(data, options) {
options = options || {};
if (data === people1 || data === people2) {
options.schema = peopleSchema;
}
dataset = data;
behavior.setData(data, options);
idx = behavior.columnEnum;
}
// Preset a default dialog options object. Used by call to toggleDialog('ColumnPicker') from features/ColumnPicker.js and by toggleDialog() defined herein.
grid.setDialogOptions({
//container: document.getElementById('dialog-container'),
settings: false
});
// add a column filter subexpression containing a single condition purely for demo purposes
if (false) { // eslint-disable-line no-constant-condition
grid.getGlobalFilter().columnFilters.add({
children: [{
column: 'total_number_of_pets_owned',
operator: '=',
operand: '3'
}],
type: 'columnFilter'
});
}
window.vent = false;
//functions for showing the grouping/rollup capabilities
var rollups = window.fin.Hypergrid.analytics.util.aggregations,
aggregates = {
totalPets: rollups.sum(2),
averagePets: rollups.avg(2),
maxPets: rollups.max(2),
minPets: rollups.min(2),
firstPet: rollups.first(2),
lastPet: rollups.last(2),
stdDevPets: rollups.stddev(2)
},
groups = [idx.BIRTH_STATE, idx.LAST_NAME, idx.FIRST_NAME];
var aggView, aggViewOn = false, doAggregates = false;
function toggleAggregates() {
if (!aggView){
aggView = new AggView(grid, {});
aggView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked) {
grid.setAggregateGroups(aggregates, groups);
aggViewOn = true;
} else {
grid.setAggregateGroups([], []);
aggViewOn = false;
}
}
function toggleTreeview() {
if (this.checked) {
treeView = new TreeView(grid, { treeColumn: 'State' });
treeView.setPipeline({ includeSorter: true, includeFilter: true });
treeView.setRelation(true, true);
} else {
treeView.setRelation(false);
treeView = undefined;
delete dataModel.pipeline; // restore original (shared) pipeline
behavior.setData(); // reset with original pipeline
}
}
var groupView, groupViewOn = false;
function toggleGrouping(){
if (!groupView){
groupView = new GroupView(grid, {});
groupView.setPipeline({ includeSorter: true, includeFilter: true });
}
if (this.checked){
grid.setGroups(groups);
groupViewOn = true;
} else {
grid.setGroups([]);
groupViewOn = false;
}
}

you may try:
(rollups.sum(11)).toFixed(2)
enclosing number in parentheses seems to make browser bypass the limit that identifier cannot start immediately after numeric literal
edited #2:
//all formatting and rendering per cell can be overridden in here
dataModel.getCell = function(config, rendererName) {
if(aggViewOn)
{
if(config.columnName == "total_pets")
{
if(typeof(config.value) == 'number')
{
config.value = config.value.toFixed(2);
}
else if(config.value && config.value.length == 3 && typeof(config.value[1]) == 'number')
{
config.value = config.value[1].toFixed(2);
}
}
}
return grid.cellRenderers.get(rendererName);
};

Related

creating default parameters when making a object using object.create

Is there a way to optionally declare dots: {} from inside Object.create?
As you can see I have tried
standard default parameter assignment
tried using a nullish coalescing
Neither work.
Any guidance would be appreciated.
'use strict'
let Carousel = function(name, dots=true) {
this.name = name
this.dots = dots ?? true
}
Carousel.prototype.show = function() {
console.log(`${this.name} and ${this.dots}`)
}
window.addEventListener('DOMContentLoaded', () => {
let usps = Object.create(Carousel.prototype, {
name: { value: 'element name', writeable: false}
// dots: { value: true, writeable: false }
})
usps.show()
})
Not sure why you don't use new keyword and instead create object from prototype, but in either case, if you set default value to prototype of your object, you will get dots on it.
let Carousel = function(name, dots) {
this.name = name
this.dots = dots
}
Carousel.prototype.show = function() {
console.log(`${this.name} and ${this.dots}`)
}
Carousel.prototype.dots = true;
window.addEventListener('DOMContentLoaded', () => {
let usps = Object.create(Carousel.prototype, {
name: { value: 'element name', writeable: false},
})
usps.show() // will show that dots equals true
let usps2 = Object.create(Carousel.prototype, {
name: { value: 'element name', writeable: false},
dots: { value: false, writeable: false }
});
usps2.show(); // will show that dots equals false
})
It is important, that if you will want to use new operator, you will have to modify your constructor, so if there is no dots parameter set, you will not override one with undefined:
let Carousel = function (name, dots) {
this.name = name;
if (dots !== undefined) {
this.dots = dots;
}
};
Carousel.prototype.show = function () {
console.log(`${this.name} and ${this.dots}`);
};
Carousel.prototype.dots = true;
window.addEventListener("DOMContentLoaded", () => {
let usps = new Carousel("element name");
usps.show();
let usps2 = new Carousel("element name 2", false);
usps2.show();
});

Why the gridApi.on.edit.beginCellEdit in angular-ui-grid cannot update the new drop-down options immeidiately?

I have the same problem with this one Why ui grid value drop-down box will be assigned in the event fires before beginCellEdit in angular
And have little bit difference. After I updated the editDropdownOptionArray it still keep the old value, It's only have the new value in the next click.
Hope everyone can help me with this one.
Thank you.
Here is my code snippet:
The html of the dropdown:
<div>
<form name="inputForm">
<select ng-class="'colt' + col.uid"
ui-grid-edit-dropdown
ng-model="MODEL_COL_FIELD"
ng-options="field CUSTOM_FILTERS for field in editDropdownOptionsArray"></select>
</form>
</div>
The controller code:
$scope.menuColumns = [
{ displayName: 'Menu', field: 'name', enableCellEdit: false },
{
displayName: 'Access Level', field: 'accessLevelName',
editableCellTemplate: 'Scripts/application/role/directive/dropdown-menu-assignment.html',
editDropdownValueLabel: 'Access Level', editDropdownOptionsArray: userMgtConstant.menuAccessLevel
}
];
$scope.menuOptions = {
data: [],
onRegisterApi: function (gridApi) {
gridApi.edit.on.beginCellEdit($scope, function (rowEntity, colDef, event) {
if (rowEntity.parent === true) {
colDef.editDropdownOptionsArray = $scope.levelList;
} else {
colDef.editDropdownOptionsArray = $scope.childLevelList;
}
});
gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
if (rowEntity.parent !== true) {
if(rowEntity.name === 'Revenue Bench'){
var accessLevel = commonUtils.getIdFromName(rowEntity.accessLevelName, userMgtConstant.menuAccessLevel);
if(accessLevel > 1){
$scope.isShowFunctionAssignment = false;
} else if(rowEntity.functionAssignments.length !== 0) {
$scope.isShowFunctionAssignment = true;
}
}
} else {
// udpate child dropdown list menu
var index = _(userMgtConstant.menuAccessLevel).indexOf(newValue);
$scope.childLevelList = $scope.levelList.filter(function (item, i) {
return i >= index;
});
if($scope.childLevelList.length > 2){
parentSwitch = true;
}
if($scope.childLevelList.length < 3 && parentSwitch){
colDef.editDropdownOptionsArray = $scope.childLevelList;
parentSwitch = false;
}
// update all child value
_($scope.menuOptions.data).each(function (dataItem) {
if (dataItem.parent !== true) { // prevent infinite loop
dataItem.accessLevelName = newValue;
}
});
}
});
}
};
Here is the usage of the grid:
<inline-edit-grid options="menuOptions" columns="menuColumns"></inline-edit-grid>
You should look into the usage of editDropdownRowEntityOptionsArrayPath instead of editDropdownOptionsArray
From the docs :
editDropdownRowEntityOptionsArrayPath can be used as an alternative to
editDropdownOptionsArray when the contents of the dropdown depend on
the entity backing the row.
Here is a link to tutorial

SAPUI5 only update specific binding

In SAPUI5 I have a Model ("sModel") filled with metadata.
In this model I have a property "/aSelectedNumbers".
I also have a panel, of which I want to change the visibility depending on the content of the "/aSelectedNumbers" property.
update
first controller:
var oModelMeta = cv.model.recycleModel("oModelZAPRegistratieMeta", that);
//the cv.model.recycleModel function sets the model to the component
//if that hasn't been done so already, and returns that model.
//All of my views are added to a sap.m.App, which is returned in the
//first view of this component.
var aSelectedRegistratieType = [];
var aSelectedDagdelen = ["O", "M"];
oModelMeta.setProperty("/aSelectedRegistratieType", aSelectedRegistratieType);
oModelMeta.setProperty("/aSelectedDagdelen", aSelectedDagdelen);
First Panel (Which has checkboxes controlling the array in question):
sap.ui.jsfragment("fragments.data.ZAPRegistratie.Filters.RegistratieTypeFilter", {
createContent: function(oInitData) {
var oController = oInitData.oController;
var fnCallback = oInitData.fnCallback;
var oModel = cv.model.recycleModel("oModelZAPRegistratieMeta", oController);
var oPanel = new sap.m.Panel( {
content: new sap.m.Label( {
text: "Registratietype",
width: "120px"
})
});
function addCheckBox(sName, sId) {
var oCheckBox = new sap.m.CheckBox( {
text: sName,
selected: {
path: "oModelZAPRegistratieMeta>/aSelectedRegistratieType",
formatter: function(oFC) {
if (!oFC) { return false; }
console.log(oFC);
return oFC.indexOf(sId) !== -1;
}
},
select: function(oEvent) {
var aSelectedRegistratieType = oModel.getProperty("/aSelectedRegistratieType");
var iIndex = aSelectedRegistratieType.indexOf(sId);
if (oEvent.getParameters().selected) {
if (iIndex === -1) {
aSelectedRegistratieType.push(sId);
oModel.setProperty("/aSelectedRegistratieType", aSelectedRegistratieType);
}
} else {
if (iIndex !== -1) {
aSelectedRegistratieType.splice(iIndex, 1);
oModel.setProperty("/aSelectedRegistratieType", aSelectedRegistratieType);
}
}
// arrays update niet live aan properties
oModel.updateBindings(true); //******** <<===== SEE HERE
if (fnCallback) {
fnCallback(oController);
}
},
width: "120px",
enabled: {
path: "oModelZAPRegistratieMeta>/bChanged",
formatter: function(oFC) {
return oFC !== true;
}
}
});
oPanel.addContent(oCheckBox);
}
addCheckBox("Presentielijst (dag)", "1");
addCheckBox("Presentielijst (dagdelen)", "2");
addCheckBox("Uren (dagdelen)", "3");
addCheckBox("Tijd (dagdelen)", "4");
return oPanel;
}
});
Here is the panel of which the visibility is referred to in the question. Note that it DOES work after oModel.updateBindings(true) (see comment in code above), but otherwise it does not update accordingly.
sap.ui.jsfragment("fragments.data.ZAPRegistratie.Filters.DagdeelFilter", {
createContent: function(oInitData) {
var oController = oInitData.oController;
var fnCallback = oInitData.fnCallback;
var oModel = cv.model.recycleModel("oModelZAPRegistratieMeta", oController);
var oPanel = new sap.m.Panel( {
content: new sap.m.Label( {
text: "Dagdeel",
width: "120px"
}),
visible: {
path: "oModelZAPRegistratieMeta>/aSelectedRegistratieType",
formatter: function(oFC) {
console.log("visibility");
console.log(oFC);
if (!oFC) { return true; }
if (oFC.length === 0) { return true; }
return oFC.indexOf("2") !== -1;
}
}
});
console.log(oPanel);
function addCheckBox(sName, sId) {
var oCheckBox = new sap.m.CheckBox( {
text: sName,
selected: {
path: "oModelZAPRegistratieMeta>/aSelectedDagdelen",
formatter: function(oFC) {
if (!oFC) { return false; }
console.log(oFC);
return oFC.indexOf(sId) !== -1;
}
},
select: function(oEvent) {
var aSelectedDagdelen = oModel.getProperty("/aSelectedDagdelen");
var iIndex = aSelectedDagdelen.indexOf(sId);
if (oEvent.getParameters().selected) {
if (iIndex === -1) {
aSelectedDagdelen.push(sId);
oModel.setProperty("/aSelectedDagdelen", aSelectedDagdelen);
}
} else {
if (iIndex !== -1) {
aSelectedDagdelen.splice(iIndex, 1);
oModel.setProperty("/aSelectedDagdelen", aSelectedDagdelen);
}
}
if (fnCallback) {
fnCallback(oController);
}
},
enabled: {
path: "oModelZAPRegistratieMeta>/bChanged",
formatter: function(oFC) {
return oFC !== true;
}
},
width: "120px"
});
oPanel.addContent(oCheckBox);
}
addCheckBox("Ochtend", "O", true);
addCheckBox("Middag", "M", true);
addCheckBox("Avond", "A");
addCheckBox("Nacht", "N");
return oPanel;
}
});
The reason that the model doesn´t trigger a change event is that the reference to the Array does not change.
A possible way to change the value is to create a new Array everytime you read it from the model:
var newArray = oModel.getProperty("/aSelectedNumbers").slice();
// do your changes to the array
// ...
oModel.setProperty("/aSelectedNumbers", newArray);
This JSBin illustrates the issue.

How can I separate certain object keys into their own array?

This is my first question on here. Doesn't appear to be asked elsewhere, but then again I'm not sure exactly how to phrase my question.
How can I transform an array that looks like this:
var message = {
pay_key: '12345',
'transaction[0].sender_id': 'abc',
'transaction[0].is_primary_receiver': 'false',
'transaction[0].id': 'def',
'transaction[1].sender_id': 'xyz',
'transaction[1].is_primary_receiver': 'false',
'transaction[1].id': 'tuv',
};
into something like this:
{
pay_key : '12345',
transaction : [
{
sender_id : 'abc',
is_primary_receiver : 'false',
id : 'def'
},
{
sender_id : 'xyz',
is_primary_receiver : 'false',
id : 'tuv'
}
]
}
I have no control over the format of the first object as it comes from an external service. I am trying to insert the message object into a MongoDB collection, but when I try to do an insert as-is, I get an error. So I'm trying to put it into the correct form.
Should I be using Underscore for this? I've played around with _.each but can't get it to work.
my take..
var message = {
pay_key: '12345',
'transaction[0].sender_id': 'abc',
'transaction[0].is_primary_receiver': 'false',
'transaction[0].id': 'def',
'transaction[1].sender_id': 'xyz',
'transaction[1].is_primary_receiver': 'false',
'transaction[1].id': 'tuv',
};
message.transaction=[];
for (var p in message) {
var m = p.match(/^transaction\[(\d+)\]\.(.*)/);
if (m&&m[1]&&m[2]) {
message.transaction[m[1]]=message.transaction[m[1]]||{};
message.transaction[m[1]][m[2]]=message[p];
delete message[p];
}
}
Here's a generic function I just whipped up
function makeObject(message) {
var retObj = {},
makePath = function (p, pos) {
if (/\[\d+\]$/.test(p)) {
var q = p.split(/[\[\]]/),
r = q[0],
s = q[1];
if (!pos[r]) {
pos[r] = [];
}
return pos[r][s] = pos[r][s] || {};
}
return pos[p] = pos[p] || {};
};
for(var k in message) {
if (message.hasOwnProperty(k)) {
if (k.indexOf('.') < 0) {
retObj[k] = message[k];
}
else {
var path = k.split('.'),
pos = retObj,
last = path.pop();
path.forEach(function(p) {
pos = makePath(p, pos);
});
pos[last] = message[k];
}
}
}
return retObj;
}
It works as required, but I'm sure there's some better code to do it
Had a similar response, so adding it anyway:
Object.keys(message).forEach(function(key) {
var keySplit = key.split( /\[|\]\./g )
if ( keySplit.length != 1 ) {
if ( !message.hasOwnProperty(keySplit[0]) )
message[keySplit[0]] = [];
message[keySplit[0]][keySplit[1]] = message[keySplit[0]][keySplit[1]]||{};
message[keySplit[0]][keySplit[1]][keySplit[2]] = message[key];
delete message[key];
}
});

How to reorder kendo grid rows?

I am dynamically adding rows to kendo gid. Now i need a reorder button ,where i can able to move a row up and down . i don't want drag and drop functionality. Im able to get each row id .need some help...
<script>
$(document).ready(function () {
var grid = $("#grid").kendoGrid({
columns: [
{ field: "Control", title: "Web Control Name" },
{ field: "Value", title: "Drag & Drop Variable" },
{
command: [
{ title: "create", template: "<img class='ob-image' src='../DefaultAssets/Images/New.png' style='padding: 0 15px 0 5px;' />" },
{ title: "reorder", template: "<img class ='up-image' src='../DefaultAssets/Images/Upimages.jpg' style='padding: 0 15px 0 5px;' />" },
{ "name": "destroy", title: "" }
],
},
],
dataSource: {
data: [
{
Control: "Web Control name",
Value: "Drag & Drop Variable"
},
],
schema: {
model: {
Control: "Web Control name",
Value: "Drag & Drop Variable"
}
}
},
reorderable: true,
editable: {
// confirmation: "Are you sure that you want to delete this record?",
createAt: "bottom"
},
remove: function (e) {
}
});
var grid = $("#grid").data("kendoGrid");
$("#grid").on("click", ".ob-image", function () {
var grid = $("#grid").data("kendoGrid");
grid.addRow();
});
$("#grid").on("click", ".up-image", function () {
var row = $(this).closest("tr");
var rowIdx = $("tr", grid.tbody).index(row);
alert(rowIdx);
});
});
You can create a template column and use the data source insert and remove methods to rearrange the data items. The grid will be refreshed automatically.
$("#grid").kendoGrid({
dataSource: [
{ foo: "foo" },
{ foo: "bar" },
{ foo: "baz" }
],
columns: [
{ field: "foo" },
{ template: '<button onclick="return up(\'#=uid#\')">up</button><button onclick="return down(\'#=uid#\')">down</button>' }
]
});
function up(uid) {
var grid = $("#grid").data("kendoGrid");
var dataItem = grid.dataSource.getByUid(uid);
var index = grid.dataSource.indexOf(dataItem);
var newIndex = Math.max(0, index - 1);
if (newIndex != index) {
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
}
return false;
}
function down(uid) {
var grid = $("#grid").data("kendoGrid");
var dataItem = grid.dataSource.getByUid(uid);
var index = grid.dataSource.indexOf(dataItem);
var newIndex = Math.min(grid.dataSource.total() - 1, index + 1);
if (newIndex != index) {
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
}
return false;
}
Here is a live demo: http://jsbin.com/ExOgiPib/1/edit
Once upon a time I was a Kendo UI user. I had a problem with sorting as well and this is how I solved it back then (after a lot of suffering):
//Sort Hack
/*
Changes all dataSources to case insensitive sorting (client side sorting).
This snipped enable case insensitive sorting on Kendo UI grid, too.
The original case sensitive comparer is a private and can't be accessed without modifying the original source code.
tested with Kendo UI version 2012.2.710 (Q2 2012 / July 2012).
*/
var CaseInsensitiveComparer = {
getterCache: {},
getter: function (expression) {
return this.getterCache[expression] = this.getterCache[expression] || new Function("d", "return " + kendo.expr(expression));
},
selector: function (field) {
return jQuery.isFunction(field) ? field : this.getter(field);
},
asc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a > b ? 1 : (a < b ? -1 : 0);
};
},
desc: function (field) {
var selector = this.selector(field);
return function (a, b) {
if ((selector(a).toLowerCase) && (selector(b).toLowerCase)) {
a = selector(a).toLowerCase(); // the magical part
b = selector(b).toLowerCase();
}
return a < b ? 1 : (a > b ? -1 : 0);
};
},
create: function (descriptor) {
return this[descriptor.dir.toLowerCase()](descriptor.field);
},
combine: function (comparers) {
return function (a, b) {
var result = comparers[0](a, b),
idx,
length;
for (idx = 1, length = comparers.length; idx < length; idx++) {
result = result || comparers[idx](a, b);
}
return result;
};
}
};
kendo.data.Query.prototype.normalizeSort = function (field, dir) {
if (field) {
var descriptor = typeof field === "string" ? { field: field, dir: dir} : field,
descriptors = jQuery.isArray(descriptor) ? descriptor : (descriptor !== undefined ? [descriptor] : []);
return jQuery.grep(descriptors, function (d) { return !!d.dir; });
}
};
kendo.data.Query.prototype.sort = function (field, dir, comparer) {
var idx,
length,
descriptors = this.normalizeSort(field, dir),
comparers = [];
comparer = comparer || CaseInsensitiveComparer;
if (descriptors.length) {
for (idx = 0, length = descriptors.length; idx < length; idx++) {
comparers.push(comparer.create(descriptors[idx]));
}
return this.orderBy({ compare: comparer.combine(comparers) });
}
return this;
};
kendo.data.Query.prototype.orderBy = function (selector) {
var result = this.data.slice(0),
comparer = jQuery.isFunction(selector) || !selector ? CaseInsensitiveComparer.asc(selector) : selector.compare;
return new kendo.data.Query(result.sort(comparer));
};
kendo.data.Query.prototype.orderByDescending = function (selector) {
return new kendo.data.Query(this.data.slice(0).sort(CaseInsensitiveComparer.desc(selector)));
};
//Sort Hack
You can implement your own solution, you can add your own functions and the order change will happen as you want.

Categories