Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Balancing speed and concision, with a preference for speed. Can we do better?
- // No ES6! Mesh is ES5-compatible.
- // Added to global namespace by calling the following:
- // g._defFunctions = function() {for (let k in _FUNCTIONS) g[k] = _FUNCTIONS[k]}
- // Vanilla
- const _FUNCTIONS = {
- SUM: function() {
- const l=arguments.length,f=function(x,y){return x+y};
- for(var i=0,s=0;i<l;i++){
- let x=arguments[i];s+=x instanceof Array?x.reduce(f,0):x
- };
- return s
- }
- }
- // Alternative - shorten sum fn using 'F' shorthand (could be used for others)
- const _FUNCTIONS = {
- F: function(_){return Function('α','β','γ','δ','"use strict";return '+_)},
- SUM: function() {
- const l=arguments.length,f=F("α+β");
- for(var i=0,s=0;i<l;i++){let x=arguments[i];s+=x instanceof Array?x.reduce(f,0):x};
- return s
- }
- }
- // Alternative 2: double shorthands via A, + reducing syntax length via get (also helps with closures)
- // ...trying to channel Arthur Whitney here
- const _FUNCTIONS = {
- F: function(_){return Function('α','β','γ','δ','"use strict";return '+_)},
- get A() {return F("Array.prototype.slice.call(α)")},
- get SUM() {const f=F("α+β"); return function() { // surely the two uses of reduce can be avoided here
- return A(arguments).reduce(function(a,b){return a+(b instanceof Array?b.reduce(f,0):b)},0);
- }}
- }
- // Of course, could always put them in the global namespace, but it may be harder for Mesh to manage insertion/deletion
- function F(_){return Function('α','β','γ','δ','"use strict";return '+_)};
- const A = F("Array.prototype.slice.call(α)");
- const SUM = (
- function() {const f=F("α+β"); return function() { // surely the two uses of reduce can be avoided here
- return A(arguments).reduce(function(a,b){return a+(b instanceof Array?b.reduce(f,0):b)},0);
- }}
- )();
- // Ideally this fn would drill into arrays with arbitrary nesting;
- // given we'll define lots of these builtin fns, it's probably worth abstracting out flattens, etc.
- // Maybe Greek letter variants take an array? Or we can define sigma in SUM? (feels wasteful)
- function _(f,x) {return x instanceof Array ? f(x) : x};
- function Σ(a) {let s=0;for(i in a)s+=_(Σ,a[i]);return s};
- // maybe we can extract out 'recursive reduce to identity' from above (params: +, 0)
- function SUM() {return Σ(arguments)};
- // And in case "for in" is slower than a straight for loop:
- function _(f,x) {return x instanceof Array ? f(x) : x};
- function l(a) {return a.length}; // define as array proto property instead?
- function Σ(a) {for(var s=0,i=l(a);i--;)s+=_(Σ,a[i]);return s};
- function SUM() {return Σ(arguments)};
- // Feels like it may be worth defining a tiny APL or K and using that...
Add Comment
Please, Sign In to add comment