Skip to content

Instantly share code, notes, and snippets.

@kyleparisi
Last active December 6, 2017 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyleparisi/2d161554743ced79d7239cb533e5aef6 to your computer and use it in GitHub Desktop.
Save kyleparisi/2d161554743ced79d7239cb533e5aef6 to your computer and use it in GitHub Desktop.
A little search algorithm for a person's name. It looks only for sequential letters in a name.
handleChange(event) {
let value = event.target.value;
if (!value) {
this.setState({ value, data: this.props.data });
return true;
}
// Let the search be async
// The the more the data is filtered the faster it will be
setTimeout(() => {
if (!Object.keys(this.state.data).length) {
this.setState({ value, data: this.props.data });
}
let data = Object.keys(this.state.data).reduce((prev, next) => {
let person = this.state.data[next];
let match = (person.first_name + person.last_name).match(
new RegExp(value.replace(/\s/g, ''), "i")
);
if (match) {
prev[next] = person;
}
return prev;
}, {});
this.setState({ value, data });
}, 0);
}
import { values } from "ramda";
/**
* Beware. Use this if you are lazy. Results might be unexpected if your
* data values contain ambiguous terms.
* @param value
* @param data
* @returns {{}}
*/
export let defaultFilter = ({value, data = {}}) => {
return Object.keys(data).reduce((prev, next) => {
let obj = data[next];
let search = values(obj).join('');
let match = (search).match(
new RegExp(value.replace(/\s/g, ""), "i")
);
if (match) {
prev[next] = obj;
}
return prev;
}, {});
}
let searchFilter = ({ value, data = {} }) => {
return Object.keys(data).reduce((prev, next) => {
let person = data[next];
let match = (person.first_name + person.last_name).match(
new RegExp(value.replace(/\s/g, ""), "i")
);
if (match) {
prev[next] = person;
}
return prev;
}, {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment