From 513042dd98da96915160047efadae3dd2736468b Mon Sep 17 00:00:00 2001 From: Thomas Fuchs Date: Wed, 18 Jul 2007 21:07:31 +0000 Subject: [PATCH] Add Array#intersect for set intersection. Returns a new array containing all items common to the array and the argument, with duplicates removed (clone of the Ruby & method). --- CHANGELOG | 4 ++++ src/array.js | 6 ++++++ test/unit/array.html | 12 ++++++++++++ 3 files changed, 22 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 4221452..bcb5e35 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,9 @@ *SVN* +* Add Array#intersect for set intersection. Returns a new array containing all items common to the array and the argument, with duplicates removed (clone of the Ruby & method). [Thomas Fuchs] + Example: + [1,1,3,5].intersect([1,2,3]) -> [1,3] + * Rename Element#getElementsBySelector to Element#select and add alias for Element#getElementsBySelector. [Thomas Fuchs] * Add Element#adjacent as a shortcut to selecting all adjacent nodes (and their children) that match a CSS selector. [Thomas Fuchs] diff --git a/src/array.js b/src/array.js index 3cc7b51..9f51547 100644 --- a/src/array.js +++ b/src/array.js @@ -85,6 +85,12 @@ Object.extend(Array.prototype, { }); }, + intersect: function(array) { + return this.uniq().findAll(function(item) { + return array.include(item); + }); + }, + clone: function() { return [].concat(this); }, diff --git a/test/unit/array.html b/test/unit/array.html index 1eb5b0f..8e0973b 100644 --- a/test/unit/array.html +++ b/test/unit/array.html @@ -147,6 +147,18 @@ assertEqual('[\'a\', 1]',['a',1].inspect()); }}, + testIntersect: function(){ with(this) { + assertEnumEqual([1,3], [1,1,3,5].intersect([1,2,3])); + assertEnumEqual([1], [1,1].intersect([1,1])); + assertEnumEqual([], [1,1,3,5].intersect([4])); + assertEnumEqual([], [1].intersect(['1'])); + + assertEnumEqual( + ['B','C','D'], + $R('A','Z').toArray().intersect($R('B','D').toArray()) + ); + }}, + testToJSON: function(){ with(this) { assertEqual('[]', [].toJSON()); assertEqual('[\"a\"]', ['a'].toJSON());