Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. var search = init(
  2. "id,first,last,emailn" +
  3. "555,John,Doe,jd@gmail.comn" +
  4. "666,Jason,scott,js@gmail.comn",
  5. "email");
  6.  
  7. search("js@gmail.com"); /// -> {"id":"666","first":"Jason","last":"scott", "email":"js@gmail.com"}
  8.  
  9. function init(text, key) {
  10. var arr = text.split('n'); /// convert text to array
  11. var keyIndex = arr[0].split(',').indexOf(key); /// returns 3
  12.  
  13. return function(value) {
  14. for (var i = 1; i < arr.length; i++) {
  15. var dataLine = arr[i].split(','); /// "666,Jason,scott,js@gmail.comn" to array
  16. if (dataLine[keyIndex] === value) { /// found match between value and id
  17. return convertToObject(arr[0].split(','), dataLine);
  18. }
  19. }
  20. return "not found";
  21. }
  22. }
  23.  
  24.  
  25.  
  26. function convertToObject(indexLine, dataLine) {
  27. /// creates an object from 2 lines: {email: "js@gmail.com",first: "Jason", id: "666", last: "scott"}
  28. var obj = {};
  29. var result = "";
  30. for (var j = 0; j < dataLine.length; j++) {
  31. obj[indexLine[j]] = dataLine[j];
  32. }
  33. return JSON.stringify(obj); /// String format;
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement