From 51bb86dc3940e8591b273243f697b57b5bebfb4c Mon Sep 17 00:00:00 2001 From: Thomas Fuchs Date: Sun, 10 Jun 2007 11:09:06 +0000 Subject: [PATCH] Add Hash.prototype.index which returns the first found property that has a specific value. Closes #8528. [Thomas Fuchs, slusarz, Mislav Marohnic] --- CHANGELOG | 6 ++++++ src/hash.js | 7 +++++++ test/unit/hash.html | 14 +++++++++++++- 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index 2e2d17a..7519e9d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,11 @@ *SVN* +* Add Hash.prototype.index which returns the first found property that has a specific value. Closes #8528. [Thomas Fuchs, slusarz, Mislav Marohnić] + Examples: + var hash = $H({a:1,b:'2'}); + hash.index(1) // -> 'a' + hash.index('1') // -> undefined + * Ensure HTMLElement exists before creating Element.extend. [Tobie Langel] * Add Number.prototype.round/ceil/floor/abs as an aliases to the respective methods in Math. Refactor to seperate number extensions from base.js. [Thomas Fuchs] diff --git a/src/hash.js b/src/hash.js index 5cbc30c..d3b089c 100644 --- a/src/hash.js +++ b/src/hash.js @@ -62,6 +62,13 @@ Object.extend(Hash.prototype, { return this.pluck('value'); }, + index: function(value) { + var match = this.detect(function(pair) { + return pair.value === value; + }); + return match && match.key; + }, + merge: function(hash) { return $H(hash).inject(this, function(mergedHash, pair) { mergedHash[pair.key] = pair.value; diff --git a/test/unit/hash.html b/test/unit/hash.html index 50dd0fe..2c8098c 100644 --- a/test/unit/hash.html +++ b/test/unit/hash.html @@ -89,7 +89,19 @@ $H(Fixtures.functions).values().map(function(i){ return typeof i })); assertEqual(9, $H(Fixtures.functions).quad(3)); assertEqual(6, $H(Fixtures.functions).plus(3)); - }}, + }}, + + testIndex: function(){ with(this) { + assertUndefined($H().index('foo')); + + assert('a', $H(Fixtures.one).index('A#')); + assert('a', $H(Fixtures.many).index('A')); + assertUndefined($H(Fixtures.many).index('Z')) + + var hash = $H({a:1,b:'2',c:1}); + assert(['a','c'].include(hash.index(1))); + assertUndefined(hash.index('1')); + }}, testMerge: function(){ with(this) { assertHashEqual(Fixtures.many, $H(Fixtures.many).merge());