Wednesday, March 15, 2017

Javascript - create fast lookup for string characters with this one-liner



This is another language shortcut, you may use it if you find yourself wanting to check if a string contains some character, and you want to do it fast, because it's inside a loop or something.

const stringy = "strings";

const stringLookup = new Set([...stringy]);

// stringLookup.has('s') === true

This is going to create a set, a hash-table-ish structure with all unique characters in the string.

The spread operator is creating an array from the string, which is essentially equivalent to stringy.split('').

So, stringLookup now has these entries { 's', 't', 'r', 'i', 'n', 'g' }.

View Set as a bag of unique elements, so it's most useful for quick character lookups.


A note about String.prototype.includes

This method uses the same algorithm used for String.prototype.indexOf, which in most implementations has an inside loop, which is not perfect for performance demanding apps.


I'm sure there are a lot of other ways, please share your favorite way of doing it in a comment.

No comments:

Post a Comment