<commit_before>package thx.promise;

import haxe.ds.Option;
using thx.core.Arrays;
import thx.core.Error;
import thx.core.Nil;
using thx.core.Options;
import thx.core.Tuple;

class Future<T> {
  public static function all<T>(arr : Array<Future<T>>) : Future<Array<T>>
    return Future.create(function(callback) {
      var results = [],
          counter = 0;
      arr.mapi(function(p, i) {
        p.then(function(value) {
          results[i] = value;
          counter++;
          if(counter == arr.length)
            callback(results);
        });
      });
    });

  public static function create<T>(handler : (T -> Void) -> Void) {
    var future = new Future<T>();
    handler(future.setState);
    return future;
  }

  public static function flatMap<T>(future : Future<Future<T>>) : Future<T> {
    var nfuture = new Future<T>();
    future.then(function(f) f.then(nfuture.setState));
    return nfuture;
  }

  public static function value<T>(v : T)
    return create(function(callback) callback(v));

  var handlers : Array<T -> Void>;
  public var state(default, null) : Option<T>;
  private function new() {
    handlers = [];
    state = None;
  }<commit_msg>simplified flatMap<commit_after>package thx.promise;

import haxe.ds.Option;
using thx.core.Arrays;
import thx.core.Error;
import thx.core.Nil;
using thx.core.Options;
import thx.core.Tuple;

class Future<T> {
  public static function all<T>(arr : Array<Future<T>>) : Future<Array<T>>
    return Future.create(function(callback) {
      var results = [],
          counter = 0;
      arr.mapi(function(p, i) {
        p.then(function(value) {
          results[i] = value;
          counter++;
          if(counter == arr.length)
            callback(results);
        });
      });
    });

  public static function create<T>(handler : (T -> Void) -> Void) {
    var future = new Future<T>();
    handler(future.setState);
    return future;
  }

  public static function flatMap<T>(future : Future<Future<T>>) : Future<T>
    return Future.create(function(callback) {
      future.then(function(future) future.then(callback));
    });

  public static function value<T>(v : T)
    return create(function(callback) callback(v));

  var handlers : Array<T -> Void>;
  public var state(default, null) : Option<T>;
  private function new() {
    handlers = [];
    state = None;
  }
{'fraction_non_alphanumeric': 0.1484308736217133, 'fraction_numerical': 0.0008481764206955047, 'mean_word_length': 2.9382303839732886, 'pattern_counts': {'":': 0, '<': 34, '<?xml version=': 0, '>': 40, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5687099', 'n_tokens_mistral': 764, 'n_tokens_neox': 746, 'n_words': 173}