Skip to content

Instantly share code, notes, and snippets.

@sharmaabhinav
Last active January 28, 2019 11:01
Show Gist options
  • Save sharmaabhinav/ab456c47ce64d451553f79c81b1f33a2 to your computer and use it in GitHub Desktop.
Save sharmaabhinav/ab456c47ce64d451553f79c81b1f33a2 to your computer and use it in GitHub Desktop.
This Gist implements functions from lodash
function multiply (a, b) {
return a * b
}
/*
Creates a function that is restricted to invoking func once.
Repeat calls to the function return the value of the first invocation.
The func is invoked with the this binding and arguments of the created function.
*/
function once (fn) {
var cacheValue = null
var isCalled = false
return function (...args) {
if (!isCalled) {
isCalled = true
cacheValue = fn(...args)
}
return cacheValue
}
}
var newfn = once(multiply)
console.log(newfn(2,3)) // 5
console.log(newfn(4,5)) // 5
console.log(newfn(4,5)) // 5
console.log(newfn(4,5)) // 5
var newfn1 = once(multiply)
console.log(newfn1(7, 10)) // 17
console.log(newfn1(9, 10)) // 17
console.log(newfn1(7, 10)) // 17
console.log(newfn1(9, 10)) // 17
var newfn2 = once(multiply)
console.log(newfn2(17, 10)) // 17
console.log(newfn2(8, 10)) // 17
console.log(newfn2(7, 10)) // 17
console.log(newfn2(9, 10)) // 17
/**
Invokes func after wait milliseconds. Any additional arguments are provided to func when it's invoked
**/
function delay (fn , time, ...args) {
var id = setTimeout(() => {
fn(...args)
}, time)
return id
}
function logging (a1, a2, a3) {
console.log(a1, a2, a3)
}
var id1 = delay(logging, 2000, 1,2,3)
var id2 = delay(logging, 3000, 1,2,3)
var id3 = delay(logging, 5000, 1,2,3)
clearTimeout(id1)
/* bind function basic implementation */
function logging (heading1, heading2, heading3, heading4) {
return `${heading1} ${heading2} ${heading3} ${heading4} ${this.name}`
}
var obj1 = {
name: 'obj1'
}
var obj2 = {
name: 'obj2',
logging: logging
}
function bind (fn, thisArg, ...args1) {
return function (...args2) {
var value = null
if (args1.length + args2.length > fn.length) {
console.log('Extra Argument(s) provided to bind function will be ignored')
}
return fn.apply(thisArg, [...args1, ...args2])
}
}
var bindfn = bind(obj2.logging, obj2, 'hi1', 'hi2')
console.log(bindfn('hi3', 'hi4'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment