Skip to content

Instantly share code, notes, and snippets.

@shuhrat
Created November 8, 2012 05:55
Show Gist options
  • Save shuhrat/4037080 to your computer and use it in GitHub Desktop.
Save shuhrat/4037080 to your computer and use it in GitHub Desktop.
var s = make(1)(2)(3)(4)(5);
var add = function (a, b) { return a + b; };
var mul = function (a, b) { return a * b; };
s(add); //15
s(mul); // 120
//Write make =)
Copy link

ghost commented Nov 10, 2012

Особо не заморачивался, первое решение выглядит как-то так:

function make(a) {
    var num = [];
    if (!isNaN(a)) {
        num.push(a);
        function f(b) {
            if(!isNaN(b)) { 
                num.push(b);
                return f; 
            } else {                        
                if (num.length) {
                    var result = num[0];
                    for (var i = 1; i < num.length; i++){
                        result = b(result, num[i]);
                    }
                    return result;
                }
            }
        }
        return f;
    }
} 

Отличная задача для собеседований, кстати. Можно сказать идеальная.

Copy link

ghost commented Nov 10, 2012

так лучшее будет

function make(a) {
    var num = [];
    if (!isNaN(a)) {
        num.push(a);
        function f(b) {
            if (!isNaN(b)) { 
                num.push(b);
                return f; 
            } else {            
                var result = num[0];
                for (var i = 1; i < num.length; i++){
                    result = b(result, num[i]);
                }
                return result;
            }
        }
        return f;
    } else
        return null;
} 

@shuhrat
Copy link
Author

shuhrat commented Dec 8, 2012

    var make = (function() {
      var cache = [],
          cacheHandler,
          result, max;

      cacheHandler = function(value) {
        if (typeof value === 'function') {
          result = null;
          max = cache.length;
          if (max >= 2) {
            result = cache[--max];
            while(max--) {
              result = value(result, cache[max]);
            }
          }
          return result;
        } else {
          cache.push(value);
          return cacheHandler;
        }
      }

      return cacheHandler;
    }());

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