callstream4euler1

solution of https://projecteuler.net/problem=1 supported for improvement with http://www.dbj.org/2010/03/30/meta-caller-pattern/

by dbjdbj

JavaScript

// utility
function print (s) {
    return setTimeout(function () { 
        document.body.innerHTML += "<li>"+s+"</li>" ; }, 1
              ) ;
};
// building block of a solution, we keep it here for simplicity
  function sum_n ( max, div ) {
  var rez = 0 ;
   while ( max-- > div) if ( max % div== 0 )  rez += max ;
    return rez ;
  }
// (c) 2010 by DBJ.ORG. MIT licence
// CallStream pattern/idiom
function euler1solution ( max_ ) {
    var rezult = 0, limit = max_ ;
    euler1solution = function (){
          var command = arguments[0], divizor = arguments[1],
              divmap = [] ;
          
        switch ( typeof command ) {
            case 'string' :
                
                divmap.push(""+divizor) ;
                
                   if ('+' == command ) {
                       rezult += sum_n ( limit,divizor ) ;
                   } else if ('-' == command ) {
                       rezult -= sum_n ( limit, divizor ) ;
                   } else {
                       rezult = "Illegal command" ;
                   }
                break;
            case 'function':
                  try {
                      rezult = command(rezult,limit, divmap );
                  } catch (x) {
                      rezult = "Exception: " + x + ", from: " + command ;
                  }
                break;
			default :
                rezult = 'illegal argument type: ' + typeof(command) ;
                break;
        }
             return euler1solution;
    }
   return euler1solution;
}
// usage
euler1solution(1000)('+',3)('+',5)('-',3*5)
( function (rez,lim,divs) {
return print(
    "For limit:" + lim + ", and divizors: {" + divs + "}, Result is:" + rez
     ) ;
}) ;