Skip to content

Instantly share code, notes, and snippets.

@fvilante
Last active March 27, 2019 21:01
Show Gist options
  • Save fvilante/f236b57140800a128684053d5827069f to your computer and use it in GitHub Desktop.
Save fvilante/f236b57140800a128684053d5827069f to your computer and use it in GitHub Desktop.
TS Algorithms
interface Node_<T> {
readonly value: T
readonly childreen: ReadonlyArray<Node_<T>> | undefined
}
const state: Node_<string> = {
value: "foo",
childreen: [
{
value: "bar",
childreen: [{
value: "foo",
childreen: undefined
},
{
value: "bar",
childreen: undefined
}]
}]
}
const mapNode = <T, U>(node: Node_<T>, mapperFn: (val:T) => U):Node_<U> =>
({
value: mapperFn(node.value),
childreen: (node.childreen === undefined)
? undefined
: node.childreen.map( nextNode => mapNode(nextNode, mapperFn))
})
@fvilante
Copy link
Author

fvilante commented Feb 25, 2019

Uma versao mutavel (side-effect) fica assim

const mapBranch = <T>(branch: Branch<T>, mapperFn: (val: T) => T): void => {
    branch.value = mapperFn(branch.value)
    if (branch.branches === undefined)
        return
    else
        branch.branches.map(nextBranch => mapBranch(nextBranch, mapperFn))
}

@fvilante
Copy link
Author

Toda mutabilidade por definicao é um side-effect.

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