Repeated diamonds shape

You can avoid repeated diamonds shape problem with Knockout by using throttling, but before you start looking for for a solution you should know about the problem.

Details Knockout Reactive Coffee Warp9

Enter number of "diamonds" from source to target and click "Calc updates" to calculate how much times the target will be updated when the source is updated.

HTML

JS

var model = new ViewModel();
model.update();
ko.applyBindings(model);

function ViewModel() {
    this.diamonds = ko.observable("2");
    this.result = ko.observable();

    this.update = function() {
        var value = parseInt(this.diamonds());
        if (value>0) {
            var source = ko.observable(1);
            var target = repeatDiamondShape(source, value);

            var updates = 0;
            var handler = target.subscribe(function(){
                updates++;
            });
            updates = 0;
            source(2);
            handler.dispose();
            this.result("Expected one update, but got "+updates);
        } else {
            this.result("Should be an integer above 0");
        }
    }
}

function repeatDiamondShape(seed, n) {
    if (n==0) return seed;
    var s1 = ko.computed(function(){ return seed() + 1; });
    var s2 = ko.computed(function(){ return seed() + 1; });
    return repeatDiamondShape(ko.computed(function(){
        return s1() + s2();
    }), n-1);
}