From 1ea7e08487a0e17dcee356500e016a1775b0d4f5 Mon Sep 17 00:00:00 2001 From: Rasmus Andersson Date: Tue, 6 Apr 2010 04:02:12 +0200 Subject: [PATCH] added Array.prototype.intersect, Array.prototype.diff and String.prototype.levenshtein --- oui/std-additions.js | 89 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/oui/std-additions.js b/oui/std-additions.js index 4ef0a0d..47d1feb 100644 --- a/oui/std-additions.js +++ b/oui/std-additions.js @@ -47,16 +47,80 @@ Object.defineConstant = function (obj, name, value, enumerable, deep) { //------------------------------------------------------------------------------ // Array +/** + * Return the first true return value from fun which is called for each value. + * fun is called on this and receives a single argument (current value). + */ Array.prototype.find = function (fun) { for (var i = 0, r; i < this.length; i++) if (r = fun.call(this, this[i])) return r; }; +/** Return a (possibly new) array which only contains unique values. */ Array.prototype.unique = function() { const x = 1; var i, tag, m = {}; for (i=0; (tag = this[i]); ++i) m[tag] = x; - return Object.keys(m); + m = Object.keys(m); + return (m.length === this.length) ? this : m; +} + +/** + * Difference between this and other array. + * + * Returns a new array with values (or indices if returnIndices) which are not + * at the same place. + * + * Example 1: + * + * oldTags = ['computer', 'car']; + * newTags = ['car', 'computer', '80s']; + * oldTags.diff(newTags) --> ['80s'] + * + * Example 2: + * + * A = [1, 2, 3, 4, 5] + * B = [1, 2, 6, 4, 5, 6, 7, 8] + * B.diff(A) => [3] // values + * B.diff(A, true) => [2] // indices + * A.diff(B) => [8, 7, 6, 6] // values + * A.diff(B, true) => [7, 6, 5, 2] // indices + */ +Array.prototype.diff = function (other, returnIndices) { + var d = [], e = -1, h, i, j, k; + for(i = other.length, k = this.length; i--;){ + for(j = k; j && (h = other[i] !== this[--j]);); + // The comparator here will be optimized away by V8 + h && (d[++e] = returnIndices ? i : other[i]); + } + return d; +} + +/** + * Return a new array which contains the intersection of this and any other + * array passed as an argument. + */ +Array.prototype.intersect = function() { + var retArr = [], k1, arr, i, k; + arr1keys: + for (k1=0,L=this.length; k1 in .