Skip to content

Code simplification, removed duplication #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 22 additions & 37 deletions sorting.currency.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,32 @@
/*globals $ */
$.fn.dataTableExt.oSort['currency-asc'] = function (a, b) {
function cleanCurrency(input) {
'use strict';

var x, y;
var output;

/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
x = (a === "-" || a === "--" || a === '' || a.toLowerCase().replace('/', '') === 'na') ? -1 : a.replace(/,/g, "");
y = (b === "-" || b === "--" || b === '' || b.toLowerCase().replace('/', '') === 'na') ? -1 : b.replace(/,/g, "");
output = (input === "-" || input === "--" || input === '' || input.toLowerCase().replace('/', '') === 'na') ? -1 : input.replace(/,/g, "");

/* Remove the currency sign */
if (typeof x === "string" && isNaN(x.substr(0, 1), 10)) {
x = x.substring(1);
}
if (typeof y === "string" && isNaN(y.substr(0, 1), 10)) {
y = y.substring(1);
if (typeof output === "string" && isNaN(output.substr(0, 1), 10)) {
output = output.substring(1);
}

/* Parse and return */
x = parseFloat(x, 10);
y = parseFloat(y, 10);

return x - y;
};
$.fn.dataTableExt.oSort['currency-desc'] = function (a, b) {
'use strict';

var x, y;

/* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */
x = (a === "-" || a === "--" || a === '' || a.toLowerCase().replace('/', '') === 'na') ? -1 : a.replace(/,/g, "");
y = (b === "-" || b === "--" || b === '' || b.toLowerCase().replace('/', '') === 'na') ? -1 : b.replace(/,/g, "");

/* Remove the currency sign */
if (typeof x === "string" && isNaN(x.substr(0, 1), 10)) {
x = x.substring(1);
}
if (typeof y === "string" && isNaN(y.substr(0, 1), 10)) {
y = y.substring(1);
output = parseFloat(output, 10);

return output;
}
$.extend( $.fn.dataTableExt.oSort, {
"currency-asc" : function (a, b) {
'use strict';
var x = cleanCurrency(a);
var y = cleanCurrency(b);
return x - y;
},
"currency-desc" : function (a, b) {
'use strict';
var x = cleanCurrency(a);
var y = cleanCurrency(b);
return y - x;
}

/* Parse and return */
x = parseFloat(x, 10);
y = parseFloat(y, 10);

return y - x;
};
});