Skip to content

Instantly share code, notes, and snippets.

@bernardo-cs
Created October 9, 2017 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bernardo-cs/adb38f8deb70082cbc2bd24f33d2f0fb to your computer and use it in GitHub Desktop.
Save bernardo-cs/adb38f8deb70082cbc2bd24f33d2f0fb to your computer and use it in GitHub Desktop.
how to remove ifs from js (angular.js) and use filters/reduce
var ids = [];
if ($scope.attendeesToggle) { ids = ids.concat($scope.eventAttendees); }
if ($scope.waitingListToggle) { ids = ids.concat($scope.eventWaitingList); }
//--------
[
{ condition: () => $scope.attendeesToggle, array: $scope.eventAttendees },
{ condition: () => $scope.waitingListToggle, array: $scope.eventWaitingList }
]
.filter(({condition}) => condition() )
.reduce((res, {array}) => res.concat(array), [])
//---------
$scope.attendees = {
toggle: true,
users: []
}
$scope.waitingList = {
toggle: true,
users: []
}
['attendees', 'waitingList'].filter((x) => x.toggle ).reduce((res, acum) => res.concat(acum), [])
//---------
$scope.attendeesToggle
$scope.eventAttendees
$scope.waitingListToggle
$scope.eventWaitingList
[
{
toggle: 'attendeesToggle', event: 'eventAttendees'
},
{
toggle: 'waitingListToggle', event: 'eventWaitingList'
},
].filter((obj) => $scope[obj.toggle])
.reduce((res, e) => $scope[obj.event], [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment