Last active
October 19, 2015 11:53
-
-
Save Alexintosh/2c381db218a9be2b2f6e to your computer and use it in GitHub Desktop.
Helper to search text inside objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
'use strict'; | |
angular | |
.module('ad-utils') | |
.factory('SearchHelper', Search); | |
function Search($log, $filter){ | |
var service = { | |
string: searchStrInObj | |
}; | |
return service; | |
function searchStrInObj(obj, str, paths){ | |
$log.debug("searching..."); | |
if(!str) return false; | |
$log.debug('String to search: ' + str); | |
str = str.toLowerCase(); | |
var res = []; | |
_.map(obj, function(v, k){ | |
var strings = str.split(" "); | |
var many = []; | |
for(var i in strings){ | |
var values = []; | |
for(var j in paths){ | |
var val = _get(v, paths[j]); | |
if( Object.prototype.toString.call( val ) === '[object Array]' ) { | |
for(var x in val){ | |
values.push( searchVal( val[x], strings[i]) ); | |
} | |
} else { | |
values.push( searchVal( _get(v, paths[j]), strings[i]) ); | |
} | |
} | |
if( _.contains(values, true) ){ | |
many.push(strings[i]); | |
} | |
} | |
if( strings.join() === many.join()){ | |
res.push(v); | |
} | |
}); | |
return res; | |
} | |
/* | |
* Search a substr in hay | |
* */ | |
function searchVal(hay, needle){ | |
var format = 'dd MMMM YYYY h:mma'; | |
if(hay instanceof Date){ | |
hay = $filter('date')(hay, format); | |
console.log(hay); | |
} | |
if( typeof hay !== "string") return false; | |
return hay.toLowerCase().indexOf( needle ) !== -1; | |
} | |
/* | |
* Allow to search into a JS object with a string in dot notation | |
* EX: | |
* _get(obj, 'detail.venue.address') | |
* */ | |
function _get(obj, propString) { | |
if (!propString) | |
return obj; | |
var prop, props = propString.split('.'); | |
for (var i = 0, iLen = props.length - 1; i < iLen; i++) { | |
prop = props[i]; | |
var candidate = obj[prop]; | |
if (candidate !== undefined) { | |
obj = candidate; | |
} else { | |
break; | |
} | |
} | |
try { | |
return obj[props[i]]; | |
} catch(e){ | |
return ''; | |
} | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment