From 5262b2c97c024d468acedb928609a27949f35b3f Mon Sep 17 00:00:00 2001 From: Chris Rossi Date: Wed, 30 Oct 2013 12:35:02 +1030 Subject: [PATCH] Code simplification, removed duplication --- sorting.currency.js | 59 +++++++++++++++++---------------------------- 1 file changed, 22 insertions(+), 37 deletions(-) diff --git a/sorting.currency.js b/sorting.currency.js index 354a68c..274ca4f 100644 --- a/sorting.currency.js +++ b/sorting.currency.js @@ -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; -}; \ No newline at end of file +}); \ No newline at end of file