Navigation
Links

Powered by Squarespace
« Different async options in .NET | Main | ReverseAsyncRead () »
Monday
Jan102011

IEnumerable & IObservable Split ()

Another IObservable<> extension method I needed was Split – just like string.Split (), but generically for any array and an IObservable<T[]>. I started first with a generic IEnumberable<T> Split<T> ():

/// <summary>
/// Returns one or more arrays that contains the subarrays in this
/// instance that are delimited by elements of a specified array.
/// </summary>
/// <typeparam name="T">type of the array</typeparam>
/// <param name="value">value to split</param>
/// <param name="separator">one or more separators</param>
/// <remarks>not efficient with separator lengths > 1</remarks>
/// <returns></returns>
public static IEnumerable<T[]> Split<T> (this T[] value, params T[] separator) {
    int separatorLength = separator.Length;
    int startingIndex = 0;
    int index = -1;
    int length;

    do {
        /* loop through each item in the separator
            * array verifing it exists in the source array */
        for (int i = 0; i < separatorLength; i++) {
            index = Array.IndexOf (value, separator[i], startingIndex);
            if (-1 == index)
                break;
        }
        if (-1 < index) {
            // delimiter matched successfully
            length = index - startingIndex;
            T[] output = new T[length];
            Array.Copy (value, startingIndex, output, 0, length);
            yield return output;
            startingIndex = index + 1;
        }
    } while (-1 < index);

    if (0 == startingIndex)
        // no match, send entire value
        yield return value;
    else {
        // no more matches, send items left
        length = value.Length - startingIndex;
        T[] output = new T[length];
        Array.Copy (value, startingIndex, output, 0, length);
    }
}

Now that I can split an array, I need to an IObservable<T[]> Split() as well:

/// <summary>
/// Splits the arrays from the source observable by the separator
/// </summary>
/// <typeparam name="TSource">type of the source array</typeparam>
/// <param name="source">source array</param>
/// <param name="separator">the separator(s)</param>
/// <returns>An observable containing the same number of items (if the
/// separator(s) are not found) or additional items by spliting the incoming
/// arrays</returns>
public static IObservable<TSource[]> Split<TSource> (
    this IObservable<TSource[]> source, params TSource[][] separator) {

    if (source == null)
        throw new ArgumentNullException ("source", "source is null.");
    if (separator.Length < 1)
        throw new ArgumentOutOfRangeException ("separator");

    IObservable<TSource[]> value = source;
    /* foreach of the delimiter arrays passed in
     * chain the call to Split () */
    separator.Run (item => value = value.Split (item));
    return value;
}

/// <summary>
/// Splits the arrays from the source observable by the delimiter
/// </summary>
/// <typeparam name="TSource">type of the source array</typeparam>
/// <param name="source">source array</param>
/// <param name="separator">the delimiter</param>
/// <returns>An observable containing the same number of items (if the
/// delimiter is not found) or additional items by spliting the incoming
/// arrays</returns>
public static IObservable<TSource[]> Split<TSource> (
    this IObservable<TSource[]> source, params TSource[] separator) {

    if (source == null)
        throw new ArgumentNullException ("source");
    if (separator.Length < 1)
        throw new ArgumentOutOfRangeException ("delimiter");

    return Observable.CreateWithDisposable<TSource[]> (observer =>
        source.Subscribe<TSource[]> (value =>
                value.Split (separator).Run (observer.OnNext),
                observer.OnError, observer.OnCompleted)
    );
}

Of course these extension methods can be further optimized and handle more use cases - especially by using IList<T> instead of array.

Reader Comments (9)

Among all designer watches, we have to mention Chopard watches since they are designed in high quality and splendid appearance all the time. Here I can not wait to introduce Mille Miglia wrist watch, a classic Chopard timing watch to all of you, and then we could appreciate its unique charms together.

Mille Miglia wrist is a real classic one without fearing the time trial, and its strong and vigorous life comes from Chopard's outpouring creations. The surprising design matching with outstanding technical characteristics makes this wrist attractive and charming immediately it appears on the market.
 
The first thing of Mille Miglia wrist GT XL Chrono 2010 watch to catch people's attention is generous and gorgeous watch case in 44mm, made of fine steel or 18k rose gold, and special long numbers on the dial plate cooperates with retro and thick design perfectly. Additionally, rhodanized gray dial plate with organic carving decorative patters remind people of the instrument board on the antique car, and the minute scale ring in black and red echoes marking colors of this legendary racing event.
 
From the technical angle, Mille Miglia GT XL Chrono 2010 is also perfect. We could appreciate the charming vibration of 28, 800 times per hour of the automatic winding movement throught the transparent watch bottom cap. The movement has been approved by COSC, and the power could be stored for about 46 hours. Furthermore, the wrist watch is also set to have stopped second device, making time set-up accurate to seconds.
 
Additionally, this timing watch is equipped with natural black rubber watch band with folding buttons in Dunlop racing tire patterns of 1960s, making lovers of racing car crazy.
 
Indeed, how could people refuse such a classic watch in high quality? Chopard watches are in reality as well in name of designer watches. patek philippe replica

October 21, 2011 | Unregistered Commenterpatek philippe replica

"The Apprentice " is a 15-episode unscripted drama in which 16 candidates from all walks of life, including both Ivy League MBA graduates and street entrepreneurs with no college education, will endure rigorous tasks each week while living together in a hip Manhattan loft apartment. The tasks will test their intelligence, chutzpah and street-smarts. They will face the challenges of living in close quarters and must compete sometimes humorous but always difficult job assignments and will be forced to think outside the box in order to outshine each other to get to the top. Upon their arrival to New York City (some for the very first time), the 16 candidates will be rushed over to Trump Tower to meet with Donald Trump, the centerpiece and driving force of this series. After splitting the group into two teams of 8, Trump then issues the first task. Teams will be given time constraints for each.Season after season, the players or characters in The Apprentice Seasons DVD Boxset appear to be people who you'd absolutely love to hate.

November 4, 2011 | Unregistered CommenterFan of The Apprentice DVD

I really vacheron constantin replica
enjoyed this post. You describe this topic hublot swiss replica
very well. I really enjoy reading your blog and I will definitely best calatrava replica
bookmark it! Keep up the interesting posts!best swiss panerai replica watches

November 9, 2011 | Unregistered Commenterswiss replica watches

These news omega watches are from the sub-standard materials, including alloys. This rapid bending grade watches and dull, but also easy to scratch.
The quality of these replica omega Seamaster 300M watches are not satisfactory, because they are made of cheap materials, they often wear them who caused the problem.

November 18, 2011 | Unregistered Commenterainimi

Normally I do not read article on blogs, but I wish to say that this write-up very forced me to try and do so! Your writing style has been surprised me. Thanks, very nice article.louis vuitton mahina

November 30, 2011 | Unregistered Commenterlouis vuitton mahina

The two annual Golden Globe Award winner Messi wear nike tiempo legend iv, harvest this year the Spanish silver boots and Champions League Golden boot and two awards, the two finalist Harvey wear nike mercurial vapor superfly iii Barca irreplaceable midfielder. In 2011 they help Barcelona won the Champions League, La Liga, the Spanish Super Cup and the European Super Cup four champion. 2008 winner C Luo wear adidas f50 adizero trx , this year was last season with Real Madrid the Spanish King's cup champion, and in 40 the European golden boot record harvest ball.

Coach of the year final list are: Manchester United coach Ferguson wear adidas adipure iv sl, Barcelona coach Guardiola wear cheap adidas soccer cleats and Real Madrid coach Mourinho. The first selected the top three Ferguson, Manchester United last season led the Premiership, Champions League runner-up; Mourinho wear adidas adipower predator trx is the best coach winner; melon handsome also nominated last year.

FIFA also released Messi wear nike total 90 laser iv to Arsenal's goal in the annual best goal" Ferenc Puskas Award" before three, two other selected Neymar wear nike ctr360 maestri ii elite even had several people broke and Rooney wear cheap nike soccer cleats in the Manchester Derby barb scored goals.

In addition, the 2011 World Soccer Miss list of three candidates also released last night, Brazil, Japan and the United States of America Marta 's Zesuixi w Bach, the final cut. The women's coach of the year before three are Japan, the United States of America 's coach Zuo Zuomu coach PIA and France boss beanie.

December 6, 2011 | Unregistered Commentersoccer cleats

Your website have very interesting article. I got knowledge from here. Besides that, your blog is so popular among the searchers from search engines. It means yours website is very goodAlarm Monitoring Houston [url=http://www.smithmonitoring.com/houston-security/]Alarm Monitoring Houston[/url]

December 7, 2011 | Unregistered CommenterAlarm Monitoring Houston

David Villa ( first half ) injured truce, missed the European Cup the possibility is nike mercurial very large, so the Spanish fans generally will hope in another striker Torres. Now Torres wear nike ctr360 state in the doldrums, how to save before the horse competition shooters? -

The Spanish media thinks generally, to Torres wear nike total 90 present condition as well as the boa told his acceptance, not to say this season, just wait 2 years, Torres wear nike ctr360 maestri ii may not return to 2008 and the competitive level. Chelsea gave his game with fewer opportunities, which Torres wear nike tiempo States and confidence brings is double blow. So you want to save Torres wear adidas adipure, only to move.

Spain" sports world" on Tuesday showed the dirt, adidas predator the newspaper said today to the critical moment, Barcelona is willing to do mizuno wave cup as far as Spain's obligations, Torres will be signing to help him to return to the peak, nike tiempo legend iv but also for the Spanish national team and the fans. Of course, nike mercurial vapor superfly iii in order to get Torres, Barcelona to Chelsea out of the nike total 90 laser iv price will be relatively high," sports world" known, Barcelona would like to use three in the nike ctr360 maestri ii elite season and into the first team after the performance is quite good young Montoya wear adidas f50 adizero trx, Roberto and Cuenca exchange, Roberto and Cuenca, this season in a match against adidas adipower predator trx Barcelona have there have been more than one goal.

The newspaper also said last week to Italy, Brescia, adidas adipure iv sl Guardiola and Chelsea assistant manager Aime loa had exchanges, and was offered Aime loa to Soccer cleats swap with Torres Barca some outstanding young players. From the current situation, the Spaniard is Chelsea sale price to do pen red son trading, Nike Total 90 Laser IV and so, from Barcelona array exchange several have a great appreciation of space young players are likely to win the bet. Nike Mercurial Superfly III But for exchange candidate, Guardiola Cuenca reservations, after all the" Nike Tiempo Legend IV new Messi" said the striker this season is very eye-catching, Nike CTR360 Maestri II Guardiola is not willing to let him leave.

However, Cuenca for transfer but Adidas F50 Adizero TRX not necessarily opposed attitude. Summer from Barcelona move to Chelsea Luo Mei black is Cuenca a good Adidas Adipower Predator TRX buddy," world sports newspaper" said the Eagle over the past half year no less with the Queensland cartoon Adidas Adipure IV SL phone about London life stories. In addition, Cuenca 's girlfriend is Mizuno Supersonic Wave II a student, she intends to London universities economic professional study, and want to work there, NIke Mercurial she also hopes to move to Cuenca. In other words, even if Cuenca did not want to leave Barcelona, Nike CTR360 but I also have to take care of family feeling.

Barcelona two teams now a galaxy of talents, Nike Tiempo and make three young fellow long-term do not play games, out of the transaction may have success. Nike Total 90 Now this Chelsea team structure is serious ageing, there are 3 outstanding young players, Adidas Adipure plus their technical ability to very good, boa, promote the implementation of the new tactics will be of great help. Adidas F50 AdiZero

However, December 28th is the Spanish regions and Mediterranean Catholic countries in April Fool's day. Adidas adipower Predator Every year on this day, the Spanish media will launch an April Fool news competition, all that is difficult to distinguish true and false, Nike Tiempo Legend IV Elite Barcelona buy Torres deal, whether it is true, cheap soccer cleats Tencent sports will continue to follow up reports.

December 28, 2011 | Unregistered Commentersoccer cleats

Tevez determined to leave Manchester, AC Milan has been the most sincere buyers. Although the cristiano ronaldo cleats city had rejected a loan deal, but the Rossoneri after efforts, or to get substantive progress. didier drogba cleats Beijing time on December 31st, the British" Daily Mail" disclosed, Manchester City boss Mancini wear nike mercurial has confirmed that Tevez the move to AC Milan, nike ctr360 the transaction was close to completion.

As in the group stages of the Champions League and the nike total 90 Bayern competition in Munich staged a strike, Manchester City boss Mancini Tevez wear nike ctr360 maestri ii was relegate to limbo. The club suspended and fined by the punishment, made it clear that Tevez wear nike tiempo and Manchester city break, this let him stay with Al-Ittihad stadium hope to completely erase. adidas adipure This includes AC Milan, Paris Saint-Germain, Corinthians, adidas predator a number of clubs are interested in the winter transfer period the introduction of Tevez wear mizuno wave cup, of which the most active when the rossoneri. But AC Milan wants to hire Tevez as the first half of the year, lionel messi soccer cleats and then decide whether to buy, while city insists to be permanently outright, wayne rooney cleats this let the transaction once come to a deadlock.

The Milan first team at the nike tiempo legend iv Dubai winter training, Galliani also travelled to the United Arab emirates. In an interview with the media, Galliani wear nike mercurial vapor superfly iii said, Tevez is the AC Milan winter transfer only goal. Total even revealed, nike total 90 laser iv Manchester City has initially agreed to rent to buy the way, but in the summer of next year to buy the issue, nike ctr360 maestri ii elite Milan City hope to buy Tevez, the Rossoneri wear adidas f50 adizero trx hopes to have the right to choose. Beijing time on December 31st, from"adidas adipower predator trx Daily Mail" news, Manchester City boss Mancini wear adidas adipure iv sl has admitted that Tevez is about to join AC Milan, the deal will soon be settled.

Mancini wear Soccer cleats said:" we hope that this transaction success, in a week or 10 days may be completed. We wear Nike Total 90 Laser IV hope to be permanent, but Milan is ready to rent to buy. In any case, Tevez wear Nike Mercurial Superfly III is very close to the Rossoneri, the next few days it will have a final conclusion." Nike Tiempo Legend IV Manchester City boss position no doubt for this deal gives the conclusion, discussions between the two sides have Nike CTR360 Maestri II entered the final stage, Tevez joined the AC Milan steps have been irresistible.

The Adidas F50 Adizero TRX French upstart Paris Saint-Germain is currently buying Milan striker Alexandre Pato, once the transaction is successful, Adidas Adipower Predator TRX the Rossoneri will receive a lucrative move to gold. The subsequent AC Milan whether there will be signing big? Adidas Adipure IV SL According to" Rome sports newspaper" the news, Mizuno Supersonic Wave II in January the introduction of Tevez, AC Milan will continue to keep Adidas Adipower Predator TRX in touch with Manchester City, their goal is the introduction of Balotelli in the summer of next year. Nike Mercurial Vapor Superfly III FG Although Mancini for "super Mario" talent be profuse in praise, Nike Mercurial Vapor Superfly Safari III but at the same time its elusive character also make it very headache. Nike CTR360 Maestri II Elite AC Milan on Balotelli the coveted, while the latter is also very much hope for the Rossoneri wear Nike Tiempo Legend IV Elite. In July next year, super Mario wear cheap soccer cleats is likely to be put on the red shirt thereon.

Mario Fernandes ( Baja Gremio ): as" a best young player wear Nike Total 90 Laser III, the height of 1.9 meters, Fernandes was able to get along well with the right back and Nike Total 90 Laser IV two mid defenser location. Mourinho expressed a strong interest, think the Baja best young player wear Adidas Adipure IV if joined in January, will be in the team double title plays Adidas Adipure IV SL an important role.

Dede wear Adidas adipower Predator (bar a Dajiama ): known as the" new Lucio" Dede has scored 6 goals this season, Adidas F50 AdiZero Prime and he has joined the Leverkusen version of that year. Adidas F50 AdiZero TRX Real Madrid in 2012 to introduce.

January 2, 2012 | Unregistered Commentercheap soccer cleats

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>