Last active
January 7, 2020 13:55
-
-
Save MattiasFestin/e455bd80c68db6a4da51 to your computer and use it in GitHub Desktop.
uneval "polyfill"
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
let uneval = (o, noNativeFns = true) => { | |
var retVal = ''; | |
if (typeof o === 'object') { | |
if (Array.isArray(o)) { | |
retVal = '[' + o.map((el) => uneval(el)).join(',') + ']'; | |
} else if (o instanceof RegExp) { | |
retVal = o.toString(); | |
} else if (o instanceof Date) { | |
retVal = `new Date(${o})`; | |
} else if (o === null) { | |
retVal = 'null'; | |
} else if (Number.isNaN(o)) { | |
retVal = 'NaN'; | |
}else { | |
//[TODO] add support for defineProperty & getters & setters | |
retVal = '{' + Object.keys(o).map((k) => `"${k}":${uneval(o[k])}`).join(',') + '}'; | |
} | |
} else if (typeof o === 'function') { | |
let isNative: boolean = o.toString().match(/^function \(\) \{ \[native code\] \}$/); | |
if (isNative && noNativeFns) { | |
throw new Error('No native functions is allowed'); | |
} | |
retVal = `(${isNative ? o.name : o.toString()})`; | |
} else { | |
retVal = JSON.stringify(o); | |
} | |
return retVal; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By using
eval(uneval(some_value))
to test thisuneval
function, it will fail on following values:(void 0)
-0
Infinity
,-Infinity
NaN
[, ,]
new Date(1)
(function () { var x = {}; x.x = x; return x }())
Object(1)
,Object('')
,Object(false)
(function () { p = function () {}; p.toString = function () { return 'alert(/xss/)' }; return p; }())
({})