// Copyright (c) 2021 Thomas J. Otterson
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
const curry = require('functions/curry')
const curry3 = require('functions/curry3')
/**
* Executes a binary function, applying it to an argument and to the result of passing that
* argument to a unary function.
*
* This is an implementation of the **{@link module:combinators/pure.S|S}** combinator which
* drops the requirement that `f` be a curried function (it *can* be, but it doesn't have to
* be). The name "substitute" comes from the idea that rather than applying the first
* function to a value twice, it's applied to that value and a *substitution* of that value
* generated by the second function. This is a little thin in justification, but calling
* this operation "substitution" does have the weight of history behind it.
*
* This is a hook in J. It is also a monadic fork in J, BQN, or APL, but only if the left
* outer function is `identity` (or the right outer function, if the middle function is
* commutative).
*
* `substitute` itself is a function that can be used partially if so desired, as in this
* example.
*
* ```javascript
* // This is a point-free equivalent of:
* // const lastIndex = array => array.length - 1
* // const lastElement = array => array[lastIndex(array)]
*
* const lastIndex = compose (swap (sub) (1)) (prop ('length'))
* const lastElement = substitute (propOf) (lastIndex)
*
* const result = lastElement([1, 2, 3, 4, 5])
* console.log(result) // 5
* ```
*
* @param {function} f A function of two parameters. It is applied to `x` and to the result
* of `g`'s application to `x`.
* @param {function} g A function of one parameter. It is applied to `x` and the result
* given to `f` as its second argument.
* @param {*} x A value that becomes the first argument to `f` and the sole argument to `g`.
* @returns {*} The result of `f` when applied to `x` and the result of `g`.
* @alias module:combinators.substitute
*/
function substitute(f, g, x) {
return curry(f)(x)(g(x))
}
module.exports = curry3(substitute)