Skip to content
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

delete eval. #26

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
43 changes: 22 additions & 21 deletions index.js
Expand Up @@ -14,7 +14,7 @@ module.exports = thenify

function thenify($$__fn__$$) {
assert(typeof $$__fn__$$ === 'function')
return eval(createWrapper($$__fn__$$.name))
return createWrapper($$__fn__$$)
}

/**
Expand All @@ -27,7 +27,7 @@ function thenify($$__fn__$$) {

thenify.withCallback = function ($$__fn__$$) {
assert(typeof $$__fn__$$ === 'function')
return eval(createWrapper($$__fn__$$.name, true))
return createWrapper($$__fn__$$, true)
}

function createCallback(resolve, reject) {
Expand All @@ -41,23 +41,24 @@ function createCallback(resolve, reject) {
}
}

function createWrapper(name, withCallback) {
name = (name || '').replace(/\s|bound(?!$)/g, '')
withCallback = withCallback ?
'var lastType = typeof arguments[len - 1]\n'
+ 'if (lastType === "function") return $$__fn__$$.apply(self, arguments)\n'
: ''

return '(function ' + name + '() {\n'
+ 'var self = this\n'
+ 'var len = arguments.length\n'
+ withCallback
+ 'var args = new Array(len + 1)\n'
+ 'for (var i = 0; i < len; ++i) args[i] = arguments[i]\n'
+ 'var lastIndex = i\n'
+ 'return new Promise(function (resolve, reject) {\n'
+ 'args[lastIndex] = createCallback(resolve, reject)\n'
+ '$$__fn__$$.apply(self, args)\n'
+ '})\n'
+ '})'
function createWrapper(fn, withCallback) {
var name = fn.name;
name = (name || '').replace(/\s|bound(?!$)/g, '')
var newFn = function() {
var self = this
var len = arguments.length
if(withCallback){
var lastType = typeof arguments[len - 1]
if (lastType === "function") return fn.apply(self, arguments)
}
var args = new Array(len + 1)
for (var i = 0; i < len; ++i) args[i] = arguments[i]
var lastIndex = i
return new Promise(function(resolve, reject) {
args[lastIndex] = createCallback(resolve, reject)
fn.apply(self, args)
})
}
Object.defineProperty(newFn, "name", { value: name });
return newFn;
}