Inner join with linqJS

泄露秘密 提交于 2019-12-11 19:52:01

问题


I create a dateRange wich is an array of dates.

Then I have an array of day numbers like 0 for Sunday, 1 for Monday etc...

Now I want to get all dateRange dates according to the visibleWeekDays array.

The solution is in the getVisibleDateRange function.

But I want to do it with LINQ because why reinvent the wheel...

The inner or outer selector would still need a .day() because one of the selector is a momentJS object.

But to get the day of week I would need to put the ".day()" into the linqJS string which can not work...

What would be your solution with linqJS ?

// Arrange
var startDate = moment(new Date(2014, 1, 1));
var endDate = moment(new Date(2014, 1, 15));
var visibleWeekDays = [0,1]

// Act
var dates = dateFactory.dateRange(startDate, endDate);

var visibleDays = dateFactory.getVisibleDateRange(visibleWeekDays ,dates);



 function getVisibleDateRange(visibleWeekDays, dateRange) {
        var visibleDateRange = [];
        for (var i = 0; i < dateRange.length; i++) {
            for (var j = 0; j < visibleWeekDays.length; j++) {
                var currentDate = dateRange[i];
                var dayOfWeek = currentDate.day();
                var visibleDayOfWeek = visibleWeekDays[j];
                if (visibleDayOfWeek === dayOfWeek) {
                    visibleDateRange.push(currentDate);
                }
            }
        }        
        return visibleDateRange;
    }

    var visibleDateRange = Enumerable.from(visibleWeekDays).join(dateRange,"","","outer,inner=>outer + ':' + inner")

回答1:


Here's how I would write the inner join:

var dateRange = Enumerable.Range(1, 15).Select("new Date(2014, 1, $)");
var visibleWeekDays = Enumerable.From([0, 1]);

var visibleDateRange = dateRange.Join(visibleWeekDays,
    "$.getDay()", // outer selector
    "$",          // inner selector
    "$")          // result selector (select outer value, the date)
    .ToArray();

Here, I've used a more compact syntax for defining lambdas. Basically lambdas will generally have at most 4 paramters. So you can reference the nth parameter simply by adding additional $'s in the identifier. So $ refers to the first parameter, $$ the second, etc.

The parameters of the join is exactly the same as in the call you would make in LINQ. The first parameter is the inner collection, then the outer selector, inner selector, and result selector.

Since the outer collection is the dates, you have access the corresponding item and its properties. Since we want to get the result of calling date.getDay(), you simply call getDay() on the object (the first parameter).



来源:https://stackoverflow.com/questions/22671667/inner-join-with-linqjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!