Last active
December 19, 2015 11:49
-
-
Save paulkaplan/5950837 to your computer and use it in GitHub Desktop.
jQuery plugin to sort a list of measurements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($){ | |
$.fn.sortByMeasurement = function(child_type){ | |
var element = this; | |
if(!child_type) child_type = "li"; | |
var SINGLE_REGEX = /\s*(\d*)?([\.\/])?(\d*)\s*([a-zA-z]*)/; | |
function normalizeMeasurmentString( str ){ | |
str = stripBadCharacters(str); | |
if( isSingleDim(str) ) | |
return normalizeOneDim( str ); | |
else | |
return normalizeTwoDim( str ); | |
} | |
function normalizeOneDim( str ){ | |
var match = str.match(SINGLE_REGEX); | |
var value, unit; | |
value = parseInt( match[1] ); | |
if(!value) value = 0; | |
unit = match[4]; | |
if( match[2] ){ // a / or . seperator | |
if(match[2] === "/") // convert to decimal | |
value = value / parseInt( match[3] ); | |
else if(match[2] === ".") // append decimal | |
value += parseInt(match[3]) / Math.pow( 10, match[3].length ); | |
else | |
error("Separator not a / or . ---- ["+match[2]+"]") | |
} | |
if(unit !== "in"){ | |
value = convertUnits(unit, value); | |
} | |
return value; | |
} | |
function normalizeTwoDim(str){ | |
var str1 = str.split("×")[0].trim(); | |
var str2 = str.split("×")[1].trim(); | |
return normalizeOneDim(str1) * normalizeOneDim(str2); | |
} | |
function isSingleDim(str){ | |
return str.indexOf("×") === -1; | |
} | |
function error(msg){ | |
console.log("ERROR: "+msg); | |
} | |
function convertUnits(unit, value){ | |
error("conversion not implemented for: "+unit); | |
return value; | |
} | |
function stripBadCharacters(str){ | |
var plus_minus_regex = /±\s*[\d\.\/]*/ | |
var plus_minus = str.match( plus_minus_regex ); | |
if(plus_minus) | |
return str.replace(plus_minus[0], ""); | |
return str; | |
} | |
function sortElements(parent_el){ | |
parent_el.children(child_type).sort( function(a, b){ | |
var a_str = $(a).text().trim() | |
var b_str = $(b).text().trim() | |
return normalizeMeasurmentString(a_str) - normalizeMeasurmentString(b_str); | |
}).each( function(){ | |
parent_el.append( $(this) ); | |
}); | |
} | |
sortElements(this, child_type); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment