Arpith Siromoney 💬

Counting less

Removing some expensive code

A few days ago, I had written about adding a word count to Constellational, my app for posting notes online. The function used a regular expression to split the text you’ve written into an array, and filtered out empty “words” before checking its length:

     var wordCount = s.split(/\s+/).filter(w => (!!w)).length;

Today I noticed that React Native was warning me that my code was too slow. Fortunately, I’m only displaying this word count when the keyboard has been swiped down (because that’s when I’m in reading mode).

I’m going to fix that center-alignment :)

Anyway, this made speeding up the code quite easy:

   var countWords = () => {
  var words = this.state.post.data.split(/\s+/);
  return words.filter(w => !!w).length;
};
this.resetKeyboardSpace = () => {
 var newState = {
    height: this.state.fullHeight,
    isKeyboardUp: false,
    wordCount: countWords()
  };
  this.setState(newState);
};

I’m using react-native-keyboardevents to call resetKeyboardSpace() when the keyboard is dismissed. I also decided not to display the word count when it’s zero:

    if (this.state.isKeyboardUp || !this.state.wordCount) {
  var title = <Text></Text>;
} else {
 var title = <Text style={styles.title}>
    {this.state.wordCount} words
 </Text>;
}

Thats about it! If you want a home for your notes online, sign up here!