Created
December 29, 2022 13:45
-
-
Save DevGW/156ce7764dd53f5e00e940c85ddd8d0c to your computer and use it in GitHub Desktop.
Javascript :: Functions within Functions
This file contains 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
// returning price + shipping and salesTax | |
function billerBuilder(state) { | |
return function(price) { | |
if (state === 'NY') { | |
return price * 1.03 * 1.04; | |
} | |
return price * 1.05 * 1.06625; | |
} | |
} | |
// times tables | |
function timesTable(num1) { | |
return function(num2) { | |
return num1 * num2; | |
} | |
} | |
// or can write it like this: (num followed by arrow indicates a function) | |
const timesTable = multiplier => num => num * multiplier; | |
// passing in two arguments (where callback is a function) | |
function partial(callback, argA) { | |
return (argB) => { | |
return callback(argA, argB); | |
} | |
} | |
// subfunction counts the number of times function has been called (must define count in outer scope for closure) | |
function callCount() { | |
let count = 0; | |
return function() { | |
count ++; | |
return count; | |
} | |
} | |
// function to string | |
function stringify(callback) { | |
return function newfunction() { | |
let value = ''; | |
return callback(value).toString(); | |
} | |
} | |
// or like this: | |
function stringify(callback) { | |
return function() { | |
return callback().toString(); | |
} | |
} | |
// or can do it like this: | |
const stringify = (callback) => { | |
return () => { | |
return `${callback()}`; | |
} | |
} | |
// using a cache | |
function cacheSavings(callback) { | |
// create an object to store the returned values | |
// the keys will be the arguments given to the callback | |
// the values will be the returned value from the callback | |
let cache = {}; | |
return function(argument) { | |
// if the argument is not a key in the cache already... | |
if (!(argument in cache)) { | |
// ...call the callback and get the result | |
let callbackResult = callback(argument); | |
// then, add the argument and result to the cache | |
cache[argument] = callbackResult; | |
} | |
// return the cached value | |
return cache[argument]; | |
} | |
} | |
// written the other way: | |
const cacheSavings = (callback) => { | |
const cache = {}; | |
return (arg) => { | |
if (cache[arg]) { | |
return cache[arg]; | |
} | |
const result = callback(arg); | |
cache[arg] = result; | |
return result; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment