Skip to content

Instantly share code, notes, and snippets.

@uladzislau-stuk
Last active August 27, 2019 19:55
Show Gist options
  • Save uladzislau-stuk/57b922f4633c3ee4f8d2c90bcf12de4f to your computer and use it in GitHub Desktop.
Save uladzislau-stuk/57b922f4633c3ee4f8d2c90bcf12de4f to your computer and use it in GitHub Desktop.
[Recursion] #functional_programming

Make tree from Array
let categories = [
  {id: 'phone', parent: null},
  {id: 'samsung', parent: 'phone'},
  {id: 'apple', parent: 'phone'},
  {id: 'galaxy 5', parent: 'samsung'},
  {id: 'galaxy 6', parent: 'samsung'},
  {id: 'iphone 7', parent: 'apple'},
  {id: 'iphone 8', parent: 'apple'},
  {id: '64gb', parent: 'iphone 7'},
];

const makeTree = (categories, parent) => {
  var node = {};
  
  categories
      .filter(c => c.parent === parent)
      .forEach(c => node[c.id] = makeTree(categories, c.id))
  
  return node;
}

BinarySearch

  var search = (arr, value) => {
	const middle = Math.round(arr.length / 2)
	console.log(middle)
	if (arr[middle] === value) return value
	if (arr[middle] !== value && arr.length === 1) return -1
	if (arr[middle] > value) return search(arr.slice(0, middle), value)
	if (arr[middle] < value) return search(arr.slice(middle, value), value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment