Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE uniqBy] Adds Enumerable.uniqBy and Computed.uniqBy #12875

Merged
merged 1 commit into from
Apr 9, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,18 @@ for a detailed explanation.

Makes ember test helpers (`fillIn`, `click`, `triggerEvent` ...) fire native javascript events instead
of `jQuery.Event`s, maching more closely app's real usage.

* `ember-runtime-computed-uniq-by`

Introduces a computed and enumerable method "uniqBy" that allows creation of a new enumerable with unique values as determined by the given property key.

Example:

```
comments: [
{id: 1, comment: 'I\'m a duplicate comment!'},
{id: 2, comment: 'Then you should be fixed!'},
{id: 1, comment: 'I\'m a duplicate comment!'}
],
dedupedComments: Ember.computed.uniqBy('comments', 'id')
```
3 changes: 2 additions & 1 deletion features.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"ember-metal-ember-assign": true,
"ember-htmlbars-local-lookup": true,
"ember-application-engines": null,
"ember-glimmer": null
"ember-glimmer": null,
"ember-runtime-computed-uniq-by": null
}
}
47 changes: 47 additions & 0 deletions packages/ember-runtime/lib/computed/reduce_computed_macros.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ import { isArray } from 'ember-runtime/utils';
import { A as emberA } from 'ember-runtime/system/native_array';
import isNone from 'ember-metal/is_none';
import getProperties from 'ember-metal/get_properties';
import EmptyObject from 'ember-metal/empty_object';
import { guidFor } from 'ember-metal/utils';
import WeakMap from 'ember-metal/weak_map';


function reduceMacro(dependentKey, callback, initialValue) {
return computed(`${dependentKey}.[]`, function() {
let arr = get(this, dependentKey);
Expand Down Expand Up @@ -363,6 +366,50 @@ export function uniq(...args) {
});
}

/**
A computed property which returns a new array with all the unique
elements from an array, with uniqueness determined by specific key.
Example
```javascript
var Hamster = Ember.Object.extend({
uniqueFruits: Ember.computed.uniqBy('fruits', 'id')
});
var hamster = Hamster.create({
fruits: [
{ id: 1, 'banana' },
{ id: 2, 'grape' },
{ id: 3, 'peach' },
{ id: 1, 'banana' }
]
});
hamster.get('uniqueFruits'); // [ { id: 1, 'banana' }, { id: 2, 'grape' }, { id: 3, 'peach' }]
```
@method uniqBy
@for Ember.computed
@param {String} dependentKey
@param {String} propertyKey
@return {Ember.ComputedProperty} computes a new array with all the
unique elements from the dependent array
@public
*/
export function uniqBy(dependentKey, propertyKey) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fails JSHint b/c the function is declared inside the if block. Please define the function outside then export inside the if, or if that still complains the flagging in packages/ember-runtime/lib/index.js would be sufficient.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, exports always have to be in global scope. Just export this without flagging, but flag where it is attached to the global in runtime/index.js.

return computed(`${dependentKey}.[]`, function() {
var uniq = emberA();
var seen = new EmptyObject();
var list = get(this, dependentKey);
if (isArray(list)) {
list.forEach(item => {
var guid = guidFor(get(item, propertyKey));
if (!(guid in seen)) {
seen[guid] = true;
uniq.push(item);
}
});
}
return uniq;
}).readOnly();
}

/**
Alias for [Ember.computed.uniq](/api/#method_computed_uniq).

Expand Down
8 changes: 8 additions & 0 deletions packages/ember-runtime/lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ import TargetActionSupport from 'ember-runtime/mixins/target_action_support';
import Evented from 'ember-runtime/mixins/evented';
import PromiseProxyMixin from 'ember-runtime/mixins/promise_proxy';

import isEnabled from 'ember-metal/features';

import {
sum,
min,
Expand All @@ -53,6 +55,7 @@ import {
filter,
filterBy,
uniq,
uniqBy,
union,
intersect,
collect
Expand Down Expand Up @@ -115,6 +118,11 @@ EmComputed.mapBy = mapBy;
EmComputed.filter = filter;
EmComputed.filterBy = filterBy;
EmComputed.uniq = uniq;

if (isEnabled('ember-runtime-computed-uniq-by')) {
EmComputed.uniqBy = uniqBy;
}

EmComputed.union = union;
EmComputed.intersect = intersect;
EmComputed.collect = collect;
Expand Down
41 changes: 40 additions & 1 deletion packages/ember-runtime/lib/mixins/enumerable.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ import {
Mixin,
aliasMethod
} from 'ember-metal/mixin';
import { guidFor } from 'ember-metal/utils';
import { computed } from 'ember-metal/computed';
import EmptyObject from 'ember-metal/empty_object';
import isEnabled from 'ember-metal/features';
import {
propertyWillChange,
propertyDidChange
Expand Down Expand Up @@ -93,7 +96,7 @@ function iter(key, value) {
@since Ember 0.9
@private
*/
export default Mixin.create({
var Enumerable = Mixin.create({

/**
__Required.__ You must implement this method to apply this mixin.
Expand Down Expand Up @@ -1078,3 +1081,39 @@ export default Mixin.create({
});
}
});


if (isEnabled('ember-runtime-computed-uniq-by')) {
Enumerable.reopen({
/**
Returns a new enumerable that contains only items containing a unique property value.
The default implementation returns an array regardless of the receiver type.

```javascript
var arr = [{ value: 'a' }, { value: 'a' }, { value: 'b' }, { value: 'b' }];
arr.uniqBy('value'); // [{ value: 'a' }, { value: 'b' }]
```

@method uniqBy
@return {Ember.Enumerable}
@public
*/

uniqBy(key) {
var ret = emberA();
var seen = new EmptyObject();

this.forEach((item) => {
var guid = guidFor(get(item, key));
if (!(guid in seen)) {
seen[guid] = true;
ret.push(item);
}
});

return ret;
}
});
}

export default Enumerable;
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import run from 'ember-metal/run_loop';
import EmberObject from 'ember-runtime/system/object';
import setProperties from 'ember-metal/set_properties';
import ObjectProxy from 'ember-runtime/system/object_proxy';
import isEnabled from 'ember-metal/features';
import { get } from 'ember-metal/property_get';
import { set } from 'ember-metal/property_set';
import { addObserver } from 'ember-metal/observer';
Expand All @@ -18,6 +19,7 @@ import {
filter,
filterBy,
uniq,
uniqBy,
union,
intersect
} from 'ember-runtime/computed/reduce_computed_macros';
Expand Down Expand Up @@ -493,6 +495,79 @@ QUnit.test('properties values can be replaced', function() {
});
});

if (isEnabled('ember-runtime-computed-uniq-by')) {
QUnit.module('computed.uniqBy', {
setup() {
obj = EmberObject.extend({
list: null,
uniqueById: uniqBy('list', 'id')
}).create({
list: emberA([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 1, value: 'one' }
])
});
},
teardown() {
run(obj, 'destroy');
}
});

QUnit.test('uniqBy is readOnly', function() {
QUnit.throws(function() {
obj.set('uniqueById', 1);
}, /Cannot set read-only property "uniqueById" on object:/);
});
QUnit.test('does not include duplicates', function() {
deepEqual(obj.get('uniqueById'), [
{ id: 1, value: 'one' },
{ id: 2, value: 'two' }
]);
});

QUnit.test('it does not share state among instances', function() {
let MyObject = EmberObject.extend({
list: [],
uniqueByName: uniqBy('list', 'name')
});
let a = MyObject.create({ list: [{ name: 'bob' }, { name: 'mitch' }, { name: 'mitch' }] });
let b = MyObject.create({ list: [{ name: 'warren' }, { name: 'mitch' }] });

deepEqual(a.get('uniqueByName'), [{ name: 'bob' }, { name: 'mitch' }]);
// Making sure that 'mitch' appears
deepEqual(b.get('uniqueByName'), [{ name: 'warren' }, { name: 'mitch' }]);
});

QUnit.test('it handles changes to the dependent array', function() {
obj.get('list').pushObject({ id: 3, value: 'three' });

deepEqual(obj.get('uniqueById'), [
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 3, value: 'three' }
], 'The list includes three');

obj.get('list').pushObject({ id: 3, value: 'three' });

deepEqual(obj.get('uniqueById'), [
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 3, value: 'three' }
], 'The list does not include a duplicate three');
});

QUnit.test('it returns an empty array when computed on a non-array', function() {
var MyObject = EmberObject.extend({
list: null,
uniq: uniqBy('list', 'name')
});
let a = MyObject.create({ list: 'not an array' });

deepEqual(a.get('uniq'), []);
});
}

QUnit.module('computed.intersect', {
setup() {
obj = EmberObject.extend({
Expand Down
7 changes: 7 additions & 0 deletions packages/ember-runtime/tests/suites/enumerable.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {guidFor, generateGuid} from 'ember-metal/utils';
import {computed} from 'ember-metal/computed';
import {get} from 'ember-metal/property_get';
import { _addBeforeObserver } from 'ember-metal/observer';
import isEnabled from 'ember-metal/features';

var ObserverClass = EmberObject.extend({

Expand Down Expand Up @@ -298,6 +299,7 @@ import rejectTests from 'ember-runtime/tests/suites/enumerable/reject';
import sortByTests from 'ember-runtime/tests/suites/enumerable/sortBy';
import toArrayTests from 'ember-runtime/tests/suites/enumerable/toArray';
import uniqTests from 'ember-runtime/tests/suites/enumerable/uniq';
import uniqByTests from 'ember-runtime/tests/suites/enumerable/uniqBy';
import withoutTests from 'ember-runtime/tests/suites/enumerable/without';

EnumerableTests.importModuleTests(anyTests);
Expand All @@ -318,6 +320,11 @@ EnumerableTests.importModuleTests(rejectTests);
EnumerableTests.importModuleTests(sortByTests);
EnumerableTests.importModuleTests(toArrayTests);
EnumerableTests.importModuleTests(uniqTests);

if (isEnabled('ember-runtime-computed-uniq-by')) {
EnumerableTests.importModuleTests(uniqByTests);
}

EnumerableTests.importModuleTests(withoutTests);

export default EnumerableTests;
Expand Down
22 changes: 22 additions & 0 deletions packages/ember-runtime/tests/suites/enumerable/uniqBy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {SuiteModuleBuilder} from 'ember-runtime/tests/suites/suite';
import isEnabled from 'ember-metal/features';

var suite = SuiteModuleBuilder.create();

suite.module('uniqBy');

if (isEnabled('ember-runtime-computed-uniq-by')) {
suite.test('should return new instance with duplicates removed', function() {
var numbers = this.newObject([
{ id: 1, value: 'one' },
{ id: 2, value: 'two' },
{ id: 1, value: 'one' }
]);
deepEqual(numbers.uniqBy('id'), [
{ id: 1, value: 'one' },
{ id: 2, value: 'two' }
]);
});
}

export default suite;