Created
August 9, 2014 21:20
-
-
Save m1kc/0f7cf1ffcefb25197f39 to your computer and use it in GitHub Desktop.
Slightly improved http://habrahabr.ru/post/232671/
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.prototype.arrowise = function(){ | |
// удаляем комментарии, выделяем префикс "function...", аргументы и тело | |
var parsed = this.toString() | |
.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/mg, '') | |
.match(/(function.*?)\((.*?)\)\s*\{([\s\S]*)\}.*/); | |
var prefix = parsed[1], args = parsed[2], code = parsed[3]; | |
// если аргументы есть, добавляется запятая перед аргументом __cb | |
if(!/^\s*$/.test(args)) args += ','; | |
// имеем список строк и список "})" | |
// если расширять функционал до поддержки работы с исключениями, ends понадобится | |
// именно как список | |
var lines = ['(', prefix, '(', args, '__cb', '){'], ends = ['\n})']; | |
code.split('\n').forEach(function(line){ | |
// каждый выход из функции сопровождаем вызовом колбека | |
line = line.replace(/return\s*(.*?);/, 'return void __cb($1);'); | |
// проверяем, встречается ли "<-" ровно один раз | |
if(!/<-/.test(line)) return void lines.push(line, '\n'); | |
if(/<-.*?<-/.test(line)) throw new Error('"<-" is found more than 1 times in "'+line+'".'); | |
// заменяем стрелку на код вызова колбека | |
var parsed = /([\w\d_$\s,]+)<-(.+)\((.*)\)/.exec(line); | |
if(!parsed) throw new Error('"<-" is used incorrectly in "' + line + '".'); | |
lines.push(parsed[2], '('); | |
if(parsed[3]) lines.push(parsed[3], ', '); | |
lines.push('function(', parsed[1], '){\n'); | |
ends.push('\n});'); | |
}); | |
// склеиваем собранные строки и "})" | |
return eval(lines.concat(ends.reverse()).join('')); | |
}; | |
var fs = require('fs'); | |
//console.log('-- callbacks'); | |
//fs.writeFile('/tmp/m1kc.txt', 'hello world', function (error) { | |
// if (!!error) console.log('fail'); else console.log('ok'); | |
// fs.readFile('/tmp/m1kc.txt', function (error, data) { | |
// if (!!error) console.log('fail'); else console.log('ok'); | |
// console.log(data.toString()); | |
// }); | |
//}); | |
console.log('-- arrowise'); | |
make = function(){ | |
error <- fs.writeFile('/tmp/m1kc.txt', 'hello world'); | |
error, result <- fs.readFile('/tmp/m1kc.txt'); | |
console.log(result.toString()); | |
}.arrowise(); | |
//console.log(make); | |
//make = eval(make); | |
make(); |
Author
m1kc
commented
Aug 9, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment