从滤波器内部的循环返回值,不带辅助变量

时间:2018-10-26 10:20:36

标签: javascript ecmascript-6 functional-programming

我有这段代码,但是,要使其正常工作,我需要创建一个辅助变量来存储值。没有该变量,可以做到吗?也许是更实用的方法?

    const filterSo = response => {
    return response.filter((item) => {
        let shoudlReturn = false;
        for (let key in item) {
            if (filters[lowerFirst(key)]) {
                shoudlReturn = filters[lowerFirst(key)] === item[key];
            }
        }
        return shoudlReturn;
    });
};

2 个答案:

答案 0 :(得分:2)

由于答案为布尔值,因此只要知道答案为true,您就可以返回。更改条件以使用short-circuit evaluation来检查这两种情况,如果都用true来立即返回。

const filterSo = response => response.filter((item) => {
  for (let key in item) {
    if (filters[lowerFirst(key)] && filters[lowerFirst(key)] === item[key]) {
      return true;
    }
  }
  return false;
});

答案 1 :(得分:1)

看来您可以按如下方式简化代码!

train_datagen = ImageDataGenerator(rescale=1./255)

test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
        path_data_train,
        target_size=(img_width, img_height),
        batch_size=16,
        class_mode="sparse")

validation_generator = test_datagen.flow_from_directory(
        path_data_valid,
        target_size=(img_width, img_height),
        batch_size=16,
        class_mode="sparse")

nb_train_samples = 1874
nb_validation_samples = 234
epochs = 10
batch_size = 16

history = model.fit_generator(
        train_generator,
        steps_per_epoch=nb_train_samples // batch_size,
        epochs=epochs,
        validation_data=validation_generator,
        validation_steps=nb_validation_samples // batch_size,
        callbacks = [checkpointer])

Epoch 1/10
117/117 [==============================] - 42s 356ms/step - loss: 0.0850 - acc: 0.9690 - val_loss: 0.4173 - val_acc: 0.9062
Epoch 2/10
117/117 [==============================] - 42s 360ms/step - loss: 0.0690 - acc: 0.9765 - val_loss: 0.4423 - val_acc: 0.894

print (model.metrics_names)
model.evaluate_generator(validation_generator)
['loss', 'acc']
[0.39189313988909763, 0.9059829049640231]

preds = model.predict_generator(validation_generator)