Skip to content
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
10 changes: 8 additions & 2 deletions packages/optimizely-sdk/lib/utils/fns/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright 2017, 2019, Optimizely
* Copyright 2017, 2019-2020, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -15,6 +15,7 @@
*/
var uuid = require('uuid');
var _isFinite = require('lodash/isFinite');
var keyBy = require('@optimizely/js-sdk-utils').keyBy;
var MAX_NUMBER_LIMIT = Math.pow(2, 53);

module.exports = {
Expand All @@ -27,7 +28,12 @@ module.exports = {
isFinite: function(number) {
return _isFinite(number) && Math.abs(number) <= MAX_NUMBER_LIMIT;
},
keyBy: require('lodash/keyBy'),
keyBy: function(arr, key) {
if (!arr) return {};
return keyBy(arr, function(item) {
return item[key];
});
},
forEach: require('lodash/forEach'),
forOwn: require('lodash/forOwn'),
uuid: function() {
Expand Down
29 changes: 29 additions & 0 deletions packages/optimizely-sdk/lib/utils/fns/index.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,35 @@ describe('lib/utils/fns', function() {
assert.isTrue(fns.isFinite(-Math.pow(2, 53)));
});
});

describe('keyBy', function() {
it('should return correct object when a key is provided', function() {
var arr = [
{ key1: 'row1', key2: 'key2row1' },
{ key1: 'row2', key2: 'key2row2' },
{ key1: 'row3', key2: 'key2row3' },
{ key1: 'row4', key2: 'key2row4' },
];

var obj = fns.keyBy(arr, 'key1');

assert.deepEqual(obj, {
row1: { key1: 'row1', key2: 'key2row1' },
row2: { key1: 'row2', key2: 'key2row2' },
row3: { key1: 'row3', key2: 'key2row3' },
row4: { key1: 'row4', key2: 'key2row4' }
});
});

it('should return empty object when first argument is null or undefined', function() {
var obj = fns.keyBy(null, 'key1');
assert.isEmpty(obj);

obj = fns.keyBy(undefined, 'key1');
assert.isEmpty(obj);
});
});

describe('isNumber', function() {
it('should return true in case of number', function() {
assert.isTrue(fns.isNumber(3));
Expand Down