Skip to content

Instantly share code, notes, and snippets.

@sharmaabhinav
Last active January 9, 2019 10:56
Show Gist options
  • Save sharmaabhinav/fb6f0a475764eeb1229334167d811e40 to your computer and use it in GitHub Desktop.
Save sharmaabhinav/fb6f0a475764eeb1229334167d811e40 to your computer and use it in GitHub Desktop.
function isPrime (no) {
if (no === 1 || no === 0) {
return false
}
for(var start = 2; start <= Math.sqrt(no) ; start ++) {
if (no % start === 0) {
return false
}
}
return true
}
function factorial (no) {
var fact = 1
for(var start = 1; start <= no; start++) {
fact = fact * start
}
return fact
}
// iterative
function fib (term) {
var start = 0
var end = 1
var count = 1
var temp
while(count < term) {
temp = end
end = start + end
start = temp
count += 1
}
return start
}
// recursive
var map = {}
function fib1 (term) {
if (map[term]) {
return map[term]
}
if (term === 1) {
map[term] = 0
return 0
}
if (term === 2) {
map[term] = 1
return 1
}
map[term] = fib1(term-1) + fib1(term-2)
return map[term]
}
function isSorted (arr) {
if (arr.length === 0 && arr.length === 1) {
return true
}
for(var start=1;start <= arr.length-1;start++) {
if (arr[start] < arr[start-1]) {
return false
}
}
return true
}
// filter implemnetation
function filter (arr, fn) {
var newArr = []
for(var start = 0; start < arr.length; start++) {
if (fn(arr[start])) {
newArr.push(arr[start])
}
}
return newArr
}
// reduce implemnetation
function reduce (arr, fn, initial) {
var collection = initial
for(var start = 0; start < arr.length;start++) {
collection = fn(collection, arr[start])
}
return collection
}
// trim spaces
function trimSpaces (str) {
var start = 0
var end = str.length - 1
var newstr = ''
while(start <= end) {
var charCode = str[start].charCodeAt(0)
if ((charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122)) {
newstr += str[start].toLowerCase()
}
start += 1
}
return newstr
}
// case and white space insensitive palindrome checker
function isPalindrome (str) {
const newstr = trimSpaces(str)
return newstr.split('').reverse().join('') === newstr
}
function uniq (arr) {
var numbers = {}
var newArr = []
for (var start = 0; start < arr.length; start++) {
if (!numbers[arr[start]]) {
newArr.push(arr[start])
numbers[arr[start]] = true
}
}
return newArr
}
// intersection
function intersection (arr1, arr2) {
var map = arr1.reduce( (a, b) => ({...a, [b]: true}), {})
return arr2.filter((no) => !!map[no])
}
class LinkedList {
head = null
add(val) {
const node = new Node(val)
if (this.head === null) {
this.head = node
} else {
let pt = this.head
while (pt.next !== null) {
pt = pt.next
}
pt.next = node
}
return this
}
print() {
let pt = this.head
while (pt !== null) {
console.log(pt.val)
pt = pt.next
}
}
has(val) {
let pt = this.head
while (pt !== null) {
if (pt.val === val) {
return true
}
pt = pt.next
}
return false
}
}
class Node {
constructor(val) {
this.val = val
this.next = null
}
}
var ls = new LinkedList()
ls.add(1).add(2).add(3)
console.log(ls.has(3))
class BST {
constructor () {
this.root = null
}
add (val) {
const node = new TreeNode(val)
if (this.root === null) {
this.root = node
} else {
let pt = this.root
let prev = null
let direction = null
// refactor this logic complex to read
while(pt !== null) {
prev = pt
const isValueSmall = val < pt.val
pt = isValueSmall ? pt.left : pt.right
direction = isValueSmall ? 'left' : 'right'
}
if (direction === 'left') {
prev.left = node
} else {
prev.right = node
}
}
}
print () {
const root = this.root
var queue = []
queue.push(root)
while(queue.length !== 0) {
const node = queue.shift()
console.log(node.val)
if (node.left) {
queue.push(node.left)
}
if (node.right) {
queue.push(node.right)
}
}
}
has (val) {
let pt = this.root
while(pt !== null) {
if (val === pt.val) {
return true
}
pt = val < pt.val ? pt.left : pt.right
}
return false
}
}
class TreeNode {
constructor (val) {
this.val = val
this.left = null
this.right = null
}
}
console.log("----")
const bt = new BST()
bt.add(15)
bt.add(2)
bt.add(3)
bt.add(4)
bt.add(1)
bt.add(18)
bt.add(19)
bt.add(17)
console.log(bt.has(3))
console.log(bt.has(5))
bt.print()
function curry (fn) {
let totalArgs = []
return function cache () {
totalArgs = [...totalArgs, ...arguments]
return fn.length === totalArgs.length ? fn(...totalArgs) : cache
}
}
function cube (l, b, h) {
return l * b * h
}
var curriedFn1 = curry(cube)
console.log(curriedFn1(1))
console.log(curriedFn1(2))
console.log(curriedFn1(3))
function compose (...fns) {
return (...args) => fns.reduceRight((acc, fn, index) => index === fns.length - 1 ? fn(...acc) : fn(acc), args)
}
function multiply (d) {
return d * 2
}
function add (a, b) {
return a + b
}
function square (c) {
return c * c
}
const composedFunc = compose(multiply, square, add)
console.log(composedFunc(2,3))
function callback(err,data) {
if (err) {
console.error( err );
} else {
console.log( data );
}
}
// function should be called inside delay time if not timeout will happen to address of issue -> callback was not called
function timeoutify (fn , delay) {
var canBeCalled = true
var timer = setTimeout (() => {
canBeCalled = false
fn(new Error('timeout'))
}, delay)
return function (args) {
if (canBeCalled) {
clearTimeout(timer)
fn.apply(null, [null, args])
}
}
}
var fun = timeoutify(callback, 1500)
setTimeout(() => {
fun({a: 2})
}, 3000)
// combinator generator
function generateCombinations (arr) {
if (arr.length === 0) {
return []
}
var currentEle = arr.pop()
var previousCombinations = generateCombinations(arr)
return [currentEle, ...previousCombinations.map((el) => el + currentEle), ...previousCombinations]
}
function combinations (str) {
return generateCombinations(str.split(''))
}
var combinations = combinations('1234')
console.log(combinations, combinations.length)
// pemutation
function permute (str) {
var results = []
if (str.length === 1) {
results.push(str)
return results
}
var map = {}
for(var start = 0; start < str.length; start++) {
const firstChar = str[start]
const restChars = str.substring(0, start) + str.substring(start + 1)
const otherPermutations = permute(restChars)
for(var val of otherPermutations) {
if (!map[firstChar + val]) {
results.push(firstChar + val)
map[firstChar + val] = true
}
}
}
return results
}
const permutations = permute('Quick brown fox jump over the lazy dog')
console.log(permutations, permutations.length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment