雄辩的javascript 5.2母子

时间:2017-04-12 05:05:13

标签: javascript

我遇到问题,因为我的代码返回的结果与解决方案代码不同。我发现差异在于过滤功能。

链接到excersise:http://eloquentjavascript.net/code/#5.2

我的过滤功能:

public class ZoneFactory
{
    private readonly ZoneMapFactory zoneMapFactory;
    private readonly ZoneScheduleFactory zoneScheduleFactory;

    public ZoneFactory(ZoneMapFactory zoneMapFactory,
                              ZoneScheduleFactory zoneScheduleFactory)
    {
        this.zoneMapFactory = zoneMapFactory;
        this.zoneScheduleFactory = zoneScheduleFactory;
    }

    public Zone Create(zoneDetailDTO zone)
    {
        var map = zoneMapFactory.Create(zone.Map.Address, zone.Map.Latitude, zone.Map.Longitude);
        var schedule = zoneScheduleFactory.Create(zone.Schedule.StartHour, zone.Schedule.EndHour);

        return new Zone(zone.Name, 
                        zone.ProvinceId, 
                        map, 
                        schedule, 
                        zone.Tags);
    }
}

返回33个结果,而来自解决方案的过滤函数仅返回17:

//method in Startup class Asp.Net Core
public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(_ => Configuration);

        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);

        services.AddMvc();

        var containerBuilder = new ContainerBuilder();
        containerBuilder.RegisterModule<DefaultModule>();
        containerBuilder.Populate(services);
        var container = containerBuilder.Build();
        return new AutofacServiceProvider(container);
    }

public class DefaultModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<ZoneService>().As<IZoneService>();
        builder.RegisterType<ZoneRepository>().As<IZoneRepository>();
        builder.RegisterType<ProvinceService>().As<IProvinceService>();
        builder.RegisterType<ProvinceRepository>().As<IProvinceRepository>();
        builder.RegisterType<DtoFactory>().As<IDtoFactory>();
    }
}

哪一个是正确的?为什么第二个函数返回不同的结果?

第二个问题:

我不知道如何拉出母亲出生日期的映射功能。

ancestry.filter(function(p) { return p.mother != null; }) 

谢谢,KK

1 个答案:

答案 0 :(得分:1)

你得到不同结果的原因是因为你没有测试同样的东西。

您的问题中没有显示此代码:

var byName = {};
ancestry.forEach(function(person) {
  byName[person.name] = person;
});

...使用数组中每个人的属性填充byName对象,以便您可以使用byName["person's name here"]查找该人。

考虑到这一点,您的代码:

ancestry.filter(function(p) { return p.mother != null; }) 

...说过滤ancestry数组并仅保留mother属性不为空的元素。

官方答案代码:

ancestry.filter(function(person) { return byName[person.mother] != null;})

...说过滤ancestry数组并保留.mother对象中存在指定byName的元素。也就是说,指定母亲自己在ancestry数组中的那些元素 - 不是全部:Emma de Milliano是一个人的例子,其母亲不是空的但也没有她自己的条目数组。 (它正在测试!= null这一事实有点误导,因为实际上byName没有null值的属性:!= null测试在这种情况下的确如此是测试!= undefined,因为!=运算符认为nullundefined相等。)

  

我不知道如何拉出母亲出生日期的映射功能。

通过byName byName[p.mother]对象检索她的记录,可以找到母亲的详细信息。