Last active
January 9, 2023 21:35
-
-
Save josher19/8664936 to your computer and use it in GitHub Desktop.
Macros for LiveScript version 0.0.1
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
global or= this; | |
safereg$ = (it) -> RegExp " " + it.replace(/([\.\*\?\\])/g, "\\$1") + " ", "g" | |
MACRO = (op, _options, cmd, cmdName) ~> | |
MACRO.S or= {} | |
if typeof _options isnt "object" | |
cmdName = cmd | |
cmd = _options | |
_options = {} | |
if typeof cmd is "string" | |
cmdName = cmd | |
cmd = global[cmd] | |
options = | |
unary : cmd?.length == 1 | |
cmdName : cmdName or cmd.name or op | |
inline : cmd?.toString().length < 120 | |
leftAssoc : true | |
weight : op[op.length-1] | |
options <<< _options | |
MACRO.S[op] = {op,options,cmd, safeop : safereg$ op} | |
MACRO.pre = (str) -> | |
for k,v of MACRO.S | |
delim = if v.options.unary then '' else ' ` ' | |
str=str.replace(v.safeop, delim + v.options.cmdName + ' ' + delim) | |
str | |
## should be moved to test/macros.ls | |
@ror = ror = (ra, b) -> ra? and if ra.length then ra else b | |
res = MACRO '??', 'ror' | |
@dotproduct$ = (a,b) -> sum = 0; (for v,i in a then sum += v * b[i]; void;); sum | |
MACRO '.*', {'inline':false}, 'dotproduct$' | |
teststr = 'null ?? [] ?? ["a"] ?? ["fail"]' | |
testEql = (expected, actual) -> | |
console.assert actual == expected, actual, " !== ", expected | |
actual == expected | |
testEql 'null ` ror ` [] ` ror ` ["a"] ` ror ` ["fail"]', MACRO.pre teststr | |
a = [1,2,3] | |
b = a.slice!.reverse! | |
testdot = 'a .* b' | |
testEql 'a ` dotproduct$ ` b', MACRO.pre testdot | |
testEql 10, eval LiveScript.compile MACRO.pre('return ' + testdot), {-bare} | |
testEql 'a', (eval LiveScript.compile 'return ' + MACRO.pre(teststr), {-bare})[0] | |
testEql 'dotproduct$ : function : ror : function', do -> | |
[ | |
MACRO.S['.*'].options.cmdName | |
typeof MACRO.S['.*'].cmd | |
MACRO.S['??'].options.cmdName | |
typeof MACRO.S['??'].cmd | |
].join(' : ') | |
# export module | |
module?.exports = MACRO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment