Created
January 4, 2013 01:27
-
-
Save Gozala/4449153 to your computer and use it in GitHub Desktop.
Restructures items using given `f`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function restructure(input, f, start) { | |
return reducible(function(next, initial) { | |
var state = start | |
return reduce(input, function(item, result) { | |
var change = [].concat(f(item, state)) | |
state = change[0] | |
var value = change[1] | |
return value ? next(value, result) : | |
result | |
}, initial) | |
}) | |
} |
Author
Gozala
commented
Jan 4, 2013
var restructure = require("restructure")
function sort(f, left, right) {
left = map(left, function(item) { return { left: item })
right = map(right, function(item) { return { right: item })
var sorted = reductions(merge(left, right), function(state, item) {
var isLeft = 'left' in item
var value = isLeft ? item.left : item.right
buffer.push(value)
if (buffer.length > 1 && isLeft !== state.isLeft) {
buffer = buffer.sort(f)
return { buffer: buffer, value: buffer.shift(), skip: false }
} else {
return { buffer: buffer, skip: true }
}
}, { buffer: [] })
var items = filter(sorted, function(item) { return !item.skip })
return map(items, function(item) { return item.value })
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment