diff --git a/README.md b/README.md index 074fbd9..c01492f 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,7 @@ Converts the `input` to a result based on the `mapping`. - __mapping:__ An object that describes the mapping in the format `{ possibleInput: result }`. - A `possibleInput` of `_` defines a "catch-all" case; anything that doesn't match any of the other possible inputs, will trigger the catch-all case. - The `result` may be either a literal value, or a function that *produces* that value. If it's a function, the function will *only* be called when there is a match, and the return value of that call will be returned from the `matchValue` call. If you want to *return* functions rather than call them, see the `.literal` method below. + - If a function is specified, it will be called with the original `input` as its first and only argument; this makes it easier to specify the mapping object in a different place from where it is used with `matchValue`, by not needing to have it in the same lexical scope. Returns a result if a match was found, or the catch-all was hit. Throws an `Error` if no match was found *and* no catch-all was specified. @@ -125,6 +126,10 @@ Note that this also means that a custom error-throwing handler is not possible i ## Changelog +### v1.1.0 (June 3, 2020) + +* __Feature:__ A lazy function will now receive the original input value as its first and only argument. + ### v1.0.1 (June 3, 2020) * __Bugfix:__ Fixed function handling; they were interpreted as literals in non-literal mode and vice versa. It now works correctly, according to what the documentation specifies. diff --git a/index.js b/index.js index dae373a..3b83a66 100644 --- a/index.js +++ b/index.js @@ -1,8 +1,8 @@ "use strict"; -function getValue(value, functionsAreLiterals) { +function getValue(value, functionsAreLiterals, inputValue) { if (typeof value === "function" && !functionsAreLiterals) { - return value(); + return value(inputValue); } else { return value; } @@ -13,9 +13,9 @@ function doMatchValue(value, arms, functionsAreLiterals) { return value; } else if (arms[value] !== undefined) { // NOTE: We intentionally only check for `undefined` here (and below), since we want to allow the mapped-to value to be an explicit `null`. - return getValue(arms[value], functionsAreLiterals); + return getValue(arms[value], functionsAreLiterals, value); } else if (arms._ !== undefined) { - return getValue(arms._, functionsAreLiterals); + return getValue(arms._, functionsAreLiterals, value); } else { throw new Error(`No match arm found for value '${value}'`); }