Skip to content

Instantly share code, notes, and snippets.

@qntm
Last active August 1, 2020 16:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qntm/71da7880c46caf8817aad2f00283f653 to your computer and use it in GitHub Desktop.
Save qntm/71da7880c46caf8817aad2f00283f653 to your computer and use it in GitHub Desktop.
Parsing highly ambiguous Twitter trend strings
const { UNICODE, seq } = require('green-parse')
const trend = UNICODE.plus().map(chars => chars.join(''))
// match e.g. "trend1, trend2, trend3" and return ["trend1", "trend2", "trend3"]
const trends = trend.plus(', ')
// match e.g. "trend1, trend2 and trend3" and return ["trend1", "trend2", "trend3"]
const trendsAndTrend = seq([trends, ' and ', trend])
.map(([trends, and, trend]) => [...trends, trend])
const all = trends.or(trendsAndTrend)
const string = 'RIP June, Leon and June, June and Leon'
for (const value of all.parse(string)) {
console.log(value)
}
@qntm
Copy link
Author

qntm commented May 8, 2020

Twitter reported that "Leon" was "Trending with: RIP June, Leon and June, June and Leon" but provided no obvious mechanism for parsing that highly ambiguous single string into an array of trend strings. The code above uses my library green-parse to generate ten possible parses:

[ 'RIP June', 'Leon and June', 'June and Leon' ]
[ 'RIP June', 'Leon and June, June and Leon' ]
[ 'RIP June, Leon and June', 'June and Leon' ]
[ 'RIP June, Leon and June, June and Leon' ]
[ 'RIP June', 'Leon', 'June, June and Leon' ]
[ 'RIP June', 'Leon and June', 'June', 'Leon' ]
[ 'RIP June', 'Leon and June, June', 'Leon' ]
[ 'RIP June, Leon', 'June, June and Leon' ]
[ 'RIP June, Leon and June', 'June', 'Leon' ]
[ 'RIP June, Leon and June, June', 'Leon' ]

of which the first is honestly the most probable.

Disclaimer: I have no clue who these dead people are.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment