From 6820848bc55cb53005f03987733d637aff3ba4b0 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 15 Jan 2019 14:03:39 -0600 Subject: [PATCH] Add Matching A Computed Property In Function Args as a javascript til --- README.md | 3 +- ...ng-a-computed-property-in-function-args.md | 28 +++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 javascript/matching-a-computed-property-in-function-args.md diff --git a/README.md b/README.md index 694bebe..3623c6b 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_737 TILs and counting..._ +_738 TILs and counting..._ --- @@ -264,6 +264,7 @@ _737 TILs and counting..._ - [ISO-8601 Formatted Dates Are Interpreted As UTC](javascript/iso-8601-formatted-dates-are-interpreted-as-utc.md) - [Link A JavaScript Package Locally](javascript/link-a-javascript-package-locally.md) - [List Top-Level NPM Dependencies](javascript/list-top-level-npm-dependencies.md) +- [Matching A Computed Property In Function Args](javascript/matching-a-computed-property-in-function-args.md) - [Matching Multiple Values In A Switch Statement](javascript/matching-multiple-values-in-a-switch-statement.md) - [Mock A Function With Return Values Using Jest](javascript/mock-a-function-with-return-values-using-jest.md) - [New Dates Can Take Out Of Bounds Values](javascript/new-dates-can-take-out-of-bounds-values.md) diff --git a/javascript/matching-a-computed-property-in-function-args.md b/javascript/matching-a-computed-property-in-function-args.md new file mode 100644 index 0000000..d984ef8 --- /dev/null +++ b/javascript/matching-a-computed-property-in-function-args.md @@ -0,0 +1,28 @@ +# Matching A Computed Property In Function Args + +The [computed property name](http://es6-features.org/#ComputedPropertyNames) +feature of ES6 allows you to reference a variable in object assignments and +destructurings. This syntax is flexible enough that it can be used in the +arguments portion of a function declaration. In fact, it can even be matched +against another argument -- allowing the creation of some handy, yet terse +functions. + +```javascript +const get = (key, { [key]: foundValue }) => foundValue; +``` + +Notice that the first argument, `key`, will match against the computed +property name in the second argument. The `foundValue` will correspond to +whatever `key` maps to in the given object. + +This `get` function can then be used like so. + +```javascript +const stuff = { a: 1, b: 2, c: 3 }; + +console.log("Get a:", get("a", stuff)); // 1 +console.log("Get d:", get("d", stuff)); // undefined +``` + +h/t +[@sharifsbeat](https://twitter.com/sharifsbeat/status/1084235020183748610)