How to convert stringArray to function pointer collection for librarySystem - javascript

Currently I'm writing a librarySystem
And there's an stringArray ['greet','name'] as dependencies in the code example below, however I need to use this stringArray as an array of functions passing into
greetingToName() by using apply(), is there any way to convert the stringArray into An array of functions ?
function greet(){
return 'hi!';
}
function name(){
return 'name';
}
function greetingToName (greet, name) {
console.log( greet() + ' ' + name() );
}
var stringArray = ['greet','name'];
greetingToName.apply(null, stringArray); // this is not working properly , because it passes 'greet' and 'name' as string into function, instead of function pointers.

You can create an Object with those 2 functions, and pass the strings as you wanted, and then look inside the object by name.
const posiableFuncs = {
greet: () => {
return 'hi!';
},
name: () => {
return 'name';
}
};
function greetingToName(greet, name) {
console.log(posiableFuncs[greet]() + ' ' + posiableFuncs[name]());
}
const stringArray = ['greet', 'name'];
greetingToName.apply(null, stringArray);

Creating function variables and assigning them in array would do the trick.
something as below.
var g = function(){
return 'hi!';
}
var n = function(){
return 'name';
}
function greetingToName (greet, name) {
console.log( greet() + ' ' + name() );
}
var stringArray = [g,n];
Fiddle
https://jsfiddle.net/dk_dragonknight/yhL188se/

After i've read everybody's solutions here, I got huge inspiration, therefor I came up with this solution without changing the function context , what do you guys think ?
var posiableFuncs = {
greet : function(){
return 'hi! ';
},
name : function(){
return 'Mr. Awesome!';
}
}
function greetingToName (greet, name) {
console.log( greet() + ' ' + name() );
}
var stringArray = ['greet','name'];
// copy the functions and assign into arrayOfFunctions variable based on stringArray
var arrayOfFunctions = stringArray.map(function(functionName){
return posiableFuncs[functionName];
});
greetingToName.apply(window, arrayOfFunctions);

Related

execute function from a string llike this "mystring".truncate(5) [duplicate]

I'd like to be able to say something like this in javascript :
"a".distance("b")
How can I add my own distance function to the string class?
You can extend the String prototype;
String.prototype.distance = function (char) {
var index = this.indexOf(char);
if (index === -1) {
alert(char + " does not appear in " + this);
} else {
alert(char + " is " + (this.length - index) + " characters from the end of the string!");
}
};
... and use it like this;
"Hello".distance("H");
See a JSFiddle here.
String.prototype.distance = function( arg ) {
// code
};
Minimal example:
No ones mentioned valueOf.
==================================================
String.prototype.
OPERATES_ON_COPY_OF_STRING = function (
ARGUMENT
){
//:Get primitive copy of string:
var str = this.valueOf();
//:Append Characters To End:
str = str + ARGUMENT;
//:Return modified copy:
return( str );
};
var a = "[Whatever]";
var b = a.OPERATES_ON_COPY_OF_STRING("[Hi]");
console.log( a ); //: [Whatever]
console.log( b ); //: [Whatever][Hi]
==================================================
From my research into it, there is no way to edit the string in place.
Even if you use a string object instead of a string primitive.
Below does NOT work and get's really weird results in the debugger.
==================================================
String.prototype.
EDIT_IN_PLACE_DOES_NOT_WORK = function (
ARGUMENT
){
//:Get string object:
var str = this;
//:Append Characters To End:
var LN = str.length;
for( var i = 0; i < ARGUMENT.length; i++){
str[LN+i] = ARGUMENT[ i ];
};
};
var c = new String( "[Hello]" );
console.log( c );
c.EDIT_IN_PLACE_DOES_NOT_WORK("[World]");
console.log( c );
==================================================
after years (and ES6) … we have a new option how to do this:
Object.defineProperty( String.prototype, 'distance', {
value: function ( param )
{
// your code …
return 'counting distance between ' + this + ' and ' + param;
}
} );
// ... and use it like this:
const result = "a".distance( "b" );
console.log(result);
You could do this:
String.prototype.distance = function (){
//your code
}
Using prototype to add you own function to string is called a prototype I created small JavaScript code that can select elements and change its innerHTML
var dom; //you can replce this to be $ just like jQuery
dom = function(elm) {
if(typeof elm === "object") {
// already done example
//typeof document.getElementById('id') will be object
return [elm];
} else {
return document.querySelectorAll(elm);
}
} // Returns elements by all css selector eg
// .class #id id p id > p id ~ p in short any css selectors
Object.prototype.text = function(txt) { //object prototype as NodeList returned would be object or maybe displayed as [Object NodeList]
var i = 0; //loop through the elements
for(i; i < this.length; i++) {
this[i].innerHTML = txt;
}
// in this function this refers to object that this function is passed on
};
dom('.classh').text('Changed for elements with classh');
dom('#heading').text('Changed for elements with id heading'); //examples

How to call method if I have method name as string

My requirement is on phase change I have to construct method names and call the methods and subsequent methods also,here I am able to construct method name but it is as String and not able to call the method. I have followed some of the suggestion given but I couldn't achieve. Please help.
var previousPhase = $("#currentPhase").val();
var projectPhaseArray = ["requirement", "design", "construction", "testing", "release"];
var i = 0;
$("#currentPhase").change(function() {
alert(previousPhase);
i=projectPhaseArray.indexOf(previousPhase);
for (i; i < projectPhaseArray.length; i++) {
alert(projectPhaseArray[i]);
var phaseTimeLineToCall =
projectPhaseArray[i].concat("PhasePhaseTimeLines");
executeFunctionByName(phaseTimeLineToCall,window);
}
});
function executeFunctionByName(functionName, context /*, args */) {
return context[functionName].apply(context);
}
function requirementPhaseTimeLines(){
alert("In RequirementPhaseTimelines");
}
function designPhaseTimeLines(){
alert("In DesignPhaseTimelines");
}
Thanks.
Strings don't mutate, so you need to save the value back
projectPhaseArray[i] = projectPhaseArray[i].concat("PhasePhaseTimeLines");
You could use a javascript object where you store the function name as key and the function reference as value
var lookup = {
requirementPhaseTimeLines: requirementPhaseTimeLines,
designPhaseTimeLines: designPhaseTimeLines
}
Without Arguments
We have to modify executeFunctionByName slightly
function executeFunctionByName(functionName, lookup) {
return lookup[functionName]()
}
Working Example
function requirementPhaseTimeLines() {
return "In RequirementPhaseTimelines"
}
function designPhaseTimeLines() {
return "In DesignPhaseTimelines"
}
var lookup = {
requirementPhaseTimeLines: requirementPhaseTimeLines,
designPhaseTimeLines: designPhaseTimeLines
}
function executeFunctionByName(functionName, lookup) {
return lookup[functionName]()
}
console.log(
executeFunctionByName("requirementPhaseTimeLines", functions)
)
console.log(
executeFunctionByName("designPhaseTimeLines", functions)
)
With Arguments
If we want to pass in arguments we have to curry the functions we want to let execute.
function greet(word) {
return function(name) {
return word + ', ' + name + '.'
}
}
Second, we have to create a function where we can iterate trough the arguments and set each arguement value to the function we want to execute:
function setArguments(functionRef, args) {
return args.length === 1
? functionRef
: setArguments(functionRef(args[0]), args.slice(1))
}
Working Example
function greet(word) {
return function(name) {
return word + ', ' + name + '.'
}
}
var lookup = {
greet: greet
}
function getFunction(lookup, name) {
return lookup[name] || new Function()
}
function setArguments(functionRef, args) {
return args.length === 1
? functionRef
: setArguments(functionRef(args[0]), args.slice(1))
}
function executeFunctionByName(functionName, lookup, args) {
var functionRef = getFunction(lookup, functionName)
var functionRefWithArgs = setArguments(functionRef, args)
return functionRefWithArgs(args[args.length - 1])
}
console.log(
executeFunctionByName('greet', lookup, ['Hi', 'Jon'])
)

Create a simpler way of nesting functions

I'm looking to lower my overhead on code like this
foo(bar(baz("hello"))) // function hell
ideally something like this
var fbb = bind(foo, bar, baz)
foo("hello")
Does this exist? Native or library?
I looked through underscore and bind.
Underscore has the compose function which will do what you want:
var composite = _.compose(foo, bar, baz);
composite('hello');
function foo(a1){
return 'foo' + a1;
}
function bar(a2){
return 'bar' + a2;
}
function baz(a3){
return 'baz' + a3;
}
alert(foo(bar(baz("hello"))));
var composite = _.compose(foo, bar, baz);
alert( composite('hello') );
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
function getCaller(first) {
var rest = Array.prototype.slice.call(arguments, 1);
return function (value) {
return rest.reduce(function (previous, next) {
return next(previous);
}, first(value));
};
}
function foo(string) {
return string + ' world!';
}
function bar(string) {
return string + ' Hi';
}
function baz(string) {
return string + ' Mom!';
}
var caller = getCaller(foo, bar, baz);
console.log(caller('Hello'));
// Prints: Hello world! Hi Mom!
var bind = function() {
var fns = Array.prototype.slice.call(arguments).reverse();
return function(value) {
for (var key in fns) {
var fn = fns[key];
console.log(fn);
value = fn(value);
}
return value;
}
}
function plusTomato(value) {
return value + "tomato";
}
function plusPear(value) {
return value + "pear";
}
var plus = bind(plusTomato, plusPear);
var y = plus("pancake"); //pankaketomatopear
console.log(y);
var x = plusTomato(plusPear("pancake")); //pankaketomatopear
console.log(x);

retrieve names of closures declared inside function

if we have :
function parent(){
function a(){
return 'i am a';
}
function b(){
return 'i am b';
}
function c(e,f){
console.log(e+f);
}
c(a(),b());
}
Any built-in method that retrieves name of nested functions: a,b,c . Let say :
parent.closures()
// ['a','b','c']
}
DEMO
Function.prototype.closures=function() {
var that=this,fn = function(r) {
//see demo==> to reduce non-functional code
};
return this.toString().split("\n").filter(function(d) {
return d.indexOf('function ') !== -1
}).map(fn).filter(function(f) {
return f !== that.name;
})
};
then :
parent.closures()
// ['a','b','c']

How can I convert this to be an extension of the Array Prototype?

http://jsfiddle.net/ryanneufeld/Y8ZNU/
With this example I have created a queue modeled after how I assume google is handling analytics events. The thing is I'd like to convert it to be an extension of the array prototype.
What I'm trying to accomplish is that when you create a new instance of Queue and pass in a queue array, the new instance would act as an array with the extra functions I've added.
might not be perfect but it get the job done: (see the link provided by #Pointy in the comments for a good explanation as to what the pitfalls are)
function pseudoArray(name) {
if (!(this instanceof pseudoArray)) {
return new pseudoArray(name);
}
var self = this;
self.name = name || 'defaultName';
var _push = self.push;
self.push = function(args) {
console.log('"' + name + '" pushing [ ' + Array.prototype.slice.apply(arguments) + ' ]');
_push.apply(self, arguments);
};
return self;
}
pseudoArray.prototype = [];
var x = new pseudoArray('fake array');
x.push('yay', 77, function() { alert('yup'); });
x.push('things');
x.push(12);
console.log(x instanceof Array);
console.log('to string: ' + x);
console.log('length: ' + x.length);
console.log('pop result: ' + x.pop());
console.log('length: ' + x.length);
function log() {
/* workaround for chrome not playing nice and letting me .apply to console */
console.log.apply(console, arguments);
}
var q = q || [[log, 'first item q1']],
q2 = q2 || [[log, 'first time q2']];
// You'll want a console open for this.
function Queue(_q, name) {
var _q = _q || [],
name = name || 'mlQueue';
function processQueue() {
task = _q.shift();
while (task) {
func = task.shift();
func.apply(window, task);
task = _q.shift();
}
}
function init() {
_q._push = _q.push;
processQueue();
_q.push = function() {
//first push it to the array
_q._push.apply(_q, arguments);
processQueue();
};
}
function push() {
console.log(name + ' pushing values');
_q.push.apply(_q, arguments);
};
return {
init: init,
push: push,
run: processQueue,
name: name
}
};
var q = new Queue(q, 'q1');
q.push([log, 'q1 and more']);
q.init();
q.push([log, 'q1 and more']);
var q2 = new Queue(q2, 'q2');
q2.init();
q2.push([log, 'q2 and more']);​

Categories