Skip to content

Instantly share code, notes, and snippets.

@pyykkis
Last active December 20, 2015 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyykkis/6054838 to your computer and use it in GitHub Desktop.
Save pyykkis/6054838 to your computer and use it in GitHub Desktop.
Calculate sum of variable amount of values
reduce = (f, initial) -> (xs) -> Array::reduce.call xs, f, initial
butlast = (xs) -> xs.slice 0, xs.length - 1
sum = (x, y) -> x + y
addInputStream = (xs) ->
input = $('<input />')
.appendTo('#inputs')
.asEventStream('input')
.map('.target.value')
.map(parseInt)
.toProperty(0)
xs.concat [input]
removeInputStream = (xs) ->
$('input').last().remove()
butlast xs
$ ->
addInput = $('#add-input').asEventStream 'click', -> addInputStream
removeInput = $('#remove-input').asEventStream 'click', -> removeInputStream
inputs = addInput.merge(removeInput).scan [], (xs, f) -> f xs
values = inputs.flatMap Bacon.combineAsArray
sum = values.map(reduce sum, 0)
sum.assign $('#result'), 'text'
<html>
<head>
</head>
<body>
<button id="add-input">Add input</button>
<button id="remove-input">Remove input</button>
<div id="inputs"></div>
<div id="result"></div>
<script src="bower_components/jquery/jquery.js"></script>
<script src="bower_components/bacon/dist/Bacon.js"></script>
<script src="app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment