//
// Collectors.m
// GotoBus
//
// Created by haibara on 3/6/15.
//
//

#import "Collectors.h"
#import <BlocksKit/BlocksKit.h>

@implementation Collectors

+ (NSDictionary *)groupingBy:(NSArray *)elements classifierWithKeyPath:(NSString *)keyPath {
	NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
	for (id obj in elements) {
		id key = [obj valueForKeyPath:keyPath];
		if (!key) {
			continue;
		}
		NSMutableArray *array = dictionary[key];
		if (!array) {
			array = [NSMutableArray array];
			dictionary[key] = array;
		}
		[array addObject:obj];
	}
	for (id key in dictionary.allKeys) {
		dictionary[key] = [NSArray arrayWithArray:dictionary[key]];
	}
	return [NSDictionary dictionaryWithDictionary:dictionary];
}

+ (NSDictionary *)groupingBy:(NSArray *)elements classifierWithBlock:(id<NSCopying> (^) (id obj))block {
	NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
	for (id obj in elements) {
		id key = block(obj);
		if (!key) {
			continue;
		}
		NSMutableArray *array = dictionary[key];
		if (!array) {
			array = [NSMutableArray array];
			dictionary[key] = array;
		}
		[array addObject:obj];
	}
	for (id key in dictionary.allKeys) {
		dictionary[key] = [NSArray arrayWithArray:dictionary[key]];
	}
	return [NSDictionary dictionaryWithDictionary:dictionary];
}

+ (NSDictionary *)toMap:(NSArray *)elements keyMapperWithKeyPath:(NSString *)keyPath {
	return [NSDictionary dictionaryWithObjects:elements forKeys:[elements valueForKeyPath:keyPath]];
}

+ (NSDictionary *)toMap:(NSArray *)elements keyMapperWithBlock:(id<NSCopying> (^)(id))block {
	return [NSDictionary dictionaryWithObjects:elements forKeys:[elements bk_map:block]];
}

@end
