[英]Better and more performant than lodash chain
我在一些論壇上讀到,應盡可能避免使用lodash鏈,以提高性能和代碼的可讀性。 因此,有一種方法可以在集合上使用本機javascript函數替換此代碼。
_(userCollection).chain()
.map('name')
.compact()
.uniq()
.value();
像下面這樣的東西,但我不確定它像這樣寫會帶來任何附加值
_.uniq(_.compact(userCollection.map('name')))
您可以使用_.flow()
運行一系列方法:
const { flow, partialRight: pr, map, compact, uniq } = _; const getUniqeNames = flow( pr(map, 'name'), compact, uniq ); const arr = [{ name: 'John' }, {}, { name: 'Smith' }, {}, { name: 'John' }, { name: 'Smith' }] const result = getUniqeNames(arr); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
使用lodash / fp可以使 Flow更好地工作,因為這些方法是iteratee-first和data-last的。 這樣就不必對需要參數的每個方法(在lodash示例中為pr(map, 'name')
進行部分右移。
const { flow, map, compact, uniq } = _; const getUniqeNames = flow( map('name'), compact, uniq ); const arr = [{ name: 'John' }, {}, { name: 'Smith' }, {}, { name: 'John' }, { name: 'Smith' }] const result = getUniqeNames(arr); console.log(result);
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
我相信這就是您要尋找的。 無需lodash。
lodash.map
可以更改為Array.prototype.map
lodash.compact
可以更改為Array.prototype.filter
lodash.uniq
可以更改為Set
構造函數,並且可以選擇再次轉換為Array。
const users = [ {name: 'Me'}, {name: 'Someone Else'}, {name: 'Someone Else'}, {name: ''}, ]; const uniqueNames = Array.from(new Set(users .map(user => user.name) .filter(name => name))); console.log(uniqueNames);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.