Skip to content

Instantly share code, notes, and snippets.

@m1kc
Created August 9, 2014 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1kc/0f7cf1ffcefb25197f39 to your computer and use it in GitHub Desktop.
Save m1kc/0f7cf1ffcefb25197f39 to your computer and use it in GitHub Desktop.
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();
@m1kc
Copy link
Author

m1kc commented Aug 9, 2014

myhost% node demo.js
-- arrowise
hello world

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment