Last active
August 29, 2015 14:02
-
-
Save mhakes/db2408070c80f1c7f13f to your computer and use it in GitHub Desktop.
underscorejs/lodash mixin that will return the numeric values (stored as strings) in an property, object, array or combination as well as strip slashes
This file contains hidden or 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 formatData(thing) { | |
function sanitizeString(str) { | |
// discuss at: http://phpjs.org/functions/stripslashes/ | |
// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) | |
// improved by: Ates Goral (http://magnetiq.com) | |
// improved by: marrtins | |
// improved by: rezna | |
// fixed by: Mick@el | |
// bugfixed by: Onno Marsman | |
// bugfixed by: Brett Zamir (http://brett-zamir.me) | |
// input by: Rick Waldron | |
// input by: Brant Messenger (http://www.brantmessenger.com/) | |
// reimplemented by: Brett Zamir (http://brett-zamir.me) | |
// example 1: stripslashes('Kevin\'s code'); | |
// returns 1: "Kevin's code" | |
// example 2: stripslashes('Kevin\\\'s code'); | |
// returns 2: "Kevin\'s code" | |
return (str + '') | |
.replace(/\\(.?)/g, function (s, n1) { | |
switch (n1) { | |
case '\\': | |
return '\\'; | |
case '0': | |
return '\u0000'; | |
case '': | |
return ''; | |
default: | |
return n1; | |
} | |
}); | |
} | |
if (_.isUndefined(thing) || _.isNull(thing)) { | |
return; | |
} | |
if (_.isNumber(thing)) { | |
return +thing; | |
} | |
if (_.isString(thing)) { | |
if (!isNaN(parseFloat(thing)) && isFinite(thing)) { | |
return +thing; | |
} | |
return sanitizeString(thing); | |
} | |
_.each(thing, function (v, k) { | |
thing[k] = formatData(v); | |
}); | |
return thing; | |
} | |
_.mixin({ | |
'formatData': formatData | |
}); | |
/* | |
Example use: | |
var x = { | |
name: 'Matt', | |
age: "55", | |
arr: ["12", "Baseball\'s"] | |
}, | |
y = ['14','Ralph'], | |
z = "122", | |
a = { | |
num1:"12121", | |
data: ["Steve\'s","30"] | |
}, | |
b = []; | |
b.push(x,y,z,a); | |
console.log(_.formatData(b)); | |
Will produce: | |
[ | |
{ | |
age: 55, | |
arr: [12, "Baseball's] | |
name: "Matt" | |
}, | |
[14, "Ralph"], 122, { | |
data: ["Steve's",30], | |
num1: 12121 | |
} | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment