Let's say for an intance I have this template I wanted to render with hogan.js:
var template = '{{#numbers}}'
+ '{{#capitalize}}{{percentage}}{{/capitalize}} complete.\n'
+ '{{/numbers}}';
And I compile it with the ff:
var hello = hogan.compile(template);
var rendered = hello.render({
numbers: [
{ percentage: .3 },
{ percentage: .6 },
{ percentage: .8 }
],
capitalize: function() {
return function(num) {
// console.log(num);
return num * 100;
}
}
})
console.log(rendered)
How do I get the number multiplied by 100 isntead of geting NaN?
NaN complete.
NaN complete.
NaN complete.
Also, when you uncomment the line above, num = {{percentage}} instead of the number itself.
Based on the response by #akonsu, here's an example on how you might get the value for a lambda in Hogan.js.
I have two helper functions in the example, manual and automatic, which can wrap around the lambda function definition depending on the desired behavior.
var source = '{{#numbers}}'
+ 'test1 = {{#test1}}{{percentage}}{{/test1}}\n'
+ '{{/numbers}}'
+ '{{#numbers}}'
+ 'test2 = {{#test2}}{{percentage}}{{/test2}}\n'
+ '{{/numbers}}';
var template = Hogan.compile(source);
var renderer = function(context) {
return function(text) {
return template.c.compile(text, template.options).render(context);
};
};
var manual = function(lambda) {
return function(text) {
var render = renderer(this);
return lambda.call(this, text, render);
};
};
var automatic = function(lambda) {
return manual(function(text, render) {
return lambda.call(this, render(text));
});
};
var rendered = template.render({
numbers: [
{ percentage: .3 },
{ percentage: .6 },
{ percentage: .8 }
],
test1: manual(function(text, render) {
return render(text) * 100;
}),
test2: automatic(function(num) {
return num * 100;
})
});
console.log(rendered);
The output looks like this:
test1 = 30
test1 = 60
test1 = 80
test2 = 30
test2 = 60
test2 = 80
Here's a jsfiddle demonstrating the solution: http://jsfiddle.net/potatosalad/h5cU4/2/
Please note that this solution will not work with partials (if they are referenced from inside the lambda section).
The relevant code for Hogan.js 2.0.0 are lambda replace section and higher order functions.
I think this example is relevant: https://github.com/janl/mustache.js#functions. My guess is that this should help:
capitalize: function() {
return function(text, render) {
return render(text) * 100;
}
}
a similar post: How to get the value when using Lambda in Hogan.js
capitalize: function(num) {
return num * 100;
}
should work for you
Related
I'm using the CLI-Progress package from:
https://www.npmjs.com/package/cli-progress.
This is my implementation according to the documentation example:
https://github.com/npkgz/cli-progress/blob/master/examples/example-visual.js)
const b1 = new progress.Bar({
format: colors.cyan('[{bar}]') + ' {percentage}% || {value}/{total} Chunks || Speed: {speed}',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
hideCursor: true,
});
b1.start(200, 0, {
speed: "N/A"
});
let value = 0;
const speedData: number[] = [];
const timer = setInterval(() => {
value++;
speedData.push(Math.random() * 2 + 5);
const currentSpeedData = speedData.splice(-10);
b1.update(value, {
speed: (currentSpeedData.reduce((a, b) => {
return a + b;
}, 0) / currentSpeedData.length).toFixed(2) + "Mb/s"
});
if (value >= b1.getTotal()) {
clearInterval(timer);
b1.stop();
}
}, 20);
Which renders :
I have two questions about this :
Why is there two bars (I would like to get rid of the first one) ?
Why does it work since the timer function is never called (it is called recursively but there is no first call) ?
Thank you.
Can we use getters and setters without defining a method for a member?
For example, transform this
class int {
set value(val) {
this._value = val | 0; // Truncate
}
get value() {
return this._value;
}
}
var x = new int();
x.value = 5 / 2;
console.log(x.value); // shows 2 instead of 2.5
to something like this:
class int {
set (val) {
this = val | 0; // Truncate
}
get () {
return this;
}
}
var x = new int();
x = 5 / 2;
console.log(x); // shows 2 instead of 2.5
There's no operation you can tap into for when the value of a variable (x in your case) is replaced with a new value. That's just not something JavaScript has. You can't do that even with a Proxy.
Your first definition of int is probably about as close as you're going to get.
People have tried various ways of getting primitive-like things like your int. None of them is really satisfactory. For instance, this is a not-uncommon attempt:
class Int {
constructor(value) {
Object.defineProperty(this, "value", {
value: value | 0,
enumerable: true
});
}
set(value) {
return new this.constructor[Symbol.species](value);
}
valueOf() {
return this.value;
}
toString() {
return this.value; // Even though it's not a string
}
static get [Symbol.species]() {
return this;
}
}
then:
let n = new Int(5);
console.log(`n = ${n}`); // n = 5
n = n.set(n / 2);
console.log(`n = ${n}`); // n = 2
but as soon as you do something that doesn't coerce to a primitive, like:
console.log(n);
you see the object-ness of it. You have to do:
console.log(+n);
which makes it a pretty big footgun, though the immutability helps with things like let m = n..
Example:
class Int {
constructor(value) {
Object.defineProperty(this, "value", {
value: value | 0,
enumerable: true
});
}
set(value) {
return new this.constructor[Symbol.species](value);
}
valueOf() {
return this.value;
}
toString() {
return this.value; // Even though it's not a string
}
static get [Symbol.species]() {
return this;
}
}
let n = new Int(5);
console.log(`n = ${n}`); // n = 5
n = n.set(n / 2);
console.log(`n = ${n}`); // n = 2
// But
console.log(n); // (object representation of it)
After searching for quite some time, I still haven't found what I'm looking for.
There's a fair amount of examples that either require creating a new instance, or only have functions that don't return anything (which means the problem can be solved with returning this).
I hope the following example illustrates my point well:
// Say I have these functions
function aNumber(){
var max = 100, min = 0;
return (Math.floor(Math.random() * (max - min + 1)) + min);
}
function divideBy(_number, _divider){
return (_number / _divider);
}
function multiplyBy(_number, _multi){
return (_number * _multi);
}
function add(_number, _add){
return (_number + _add);
}
function subtract(_number, _sub){
return (_number - _sub);
}
// #########################################################
// I can do this with them
var test = aNumber();
test = divideBy(aNumber, 2);
test = add(aNumber, 5);
test = multiplyBy(aNumber, 3);
test = subtract(aNumber, 10);
// I would like to do this however:
var test = aNumber().divideBy(2).add(5).multiplyBy(3).subtract(10);
What would be the most efficient way to make the last line work?
Am I misinformed that this is possible without creating a new instance of something?
Yes, this requires changing the Prototype of an Object. Objects are instances. So you need to create an object to do this kind of thing.
function MyNum(value) {
this._val = value; // Having _variable is for denoting it is a private variable.
}
Initialize objects using:
var myNum = new MyNum(5);
And now using this, define these:
MyNum.prototype.divideBy = function () {}
MyNum.prototype.multiplyBy = function () {}
Don't forget to use return this; inside these functions.
Try like below for creating without instance and prototype keyword.
One more method is been added here you can set number or random number by default. if the number not specified.
var Calculator = {
setNumber: function(givenNumber) {
var max = 100,
min = 0;
this.number = (givenNumber) ? givenNumber : (Math.floor(Math.random() * (max - min + 1)) + min);
return this;
},
divideBy: function(_divider) {
this.number = (this.number / _divider);
return this;
},
multiplyBy: function(_multi) {
this.number = (this.number * _multi);
return this;
},
add: function(_add) {
this.number = (this.number + _add);
return this;
},
subtract: function(_sub) {
this.number = (this.number - _sub);
return this;
},
result: function () {
return this.number;
}
}
document.write('<pre>');
document.writeln(Calculator.setNumber(2).divideBy(2).add(5).multiplyBy(3).subtract(10).result());
document.writeln(Calculator.setNumber(4).divideBy(2).add(5).multiplyBy(3).subtract(10).number);
document.writeln(Calculator.setNumber().divideBy(2).add(5).multiplyBy(3).subtract(10).result());
document.write('</pre>');
Yes, you do need to create an instance of something. This can be a simple object literal, function constructor, etc...
The idea is that all of your methods are stored on some object, right? The only way to access those methods is to access them through that object. With this in mind, each function must RETURN the object that holds all of these methods.
A quick example
var myMethods = {
one: function() {
console.log('one');
// You can return 'this' or reference the object by name
return this;
// or
// return myMethods;
},
two: function() {
console.log('two');
return this;
}
};
myMethods.one().two().one().two();
//=> 'one', 'two', 'one', 'two'
Watch out when you reference the method directly, like so
var someMethod = myMethods.one;
someMethod() //=> undefined
This is because 'this' is now referencing the global object, which is another story for another day. Just watch out if you reference a method in this way.
Although it is generally not recommended to add functions to the prototype of JavaScript primitives, you can do what you are looking for by doing so.
function aNumber(){
var max = 100, min = 0;
return (Math.floor(Math.random() * (max - min + 1)) + min);
}
function divideBy(_number, _divider){
return (_number / _divider);
}
function multiplyBy(_number, _multi){
return (_number * _multi);
}
function add(_number, _add){
return (_number + _add);
}
function subtract(_number, _sub){
return (_number - _sub);
}
Number.prototype.divideBy = function(_divider){
return divideBy(this, _divider);
};
Number.prototype.multiplyBy = function(_multi){
return multiplyBy(this, _multi);
};
Number.prototype.add = function(_add){
return add(this, _add);
};
Number.prototype.subtract = function(_sub){
return subtract(this, _sub);
};
var test = aNumber().divideBy(2).add(5).multiplyBy(3).subtract(10);
Just like Praveen and Venkatraman said, I found the following posts about chaining, but there all have to declare a new instanse before accessing any methods for changing
method-chaining-in-javascript and beautiful-javascript-easily-create-chainable-cascading-methods-for-expressiveness
or you can use this implementation https://jsfiddle.net/ayinloya/zkys5dk6/
function aNumber() {
var max = 100;
var min = 0;
this._number = (Math.floor(Math.random() * (max - min + 1)) + min);
console.log("a init", this._number)
}
aNumber.prototype.divideBy = function(_divider) {
this._number = (this._number / _divider)
return this;
}
aNumber.prototype.multiplyBy = function(_multi) {
this._number = (this._number * _multi);
return this;
}
aNumber.prototype.add = function(_add) {
this._number = (this._number + _add);
return this;
}
aNumber.prototype.subtract = function(_sub) {
this._number = (this._number - _sub);
return this;
}
aNumber.prototype.ans = function() {
return this._number;
}
var a = new aNumber()
alert(a.add(2).subtract(1).ans())
If you don't want to pull in a library and want to have functions that are reusable (and not bind to a specific class, e.g. a Calculator). What you can do is to wrap the input into an array and then pass it through a series of map functions. In the end just take the first element and you will have your result.
function aNumber(){
var max = 100, min = 0;
return (Math.floor(Math.random() * (max - min + 1)) + min);
}
function divideBy(_number, _divider){
return (_number / _divider);
}
function multiplyBy(_number, _multi){
return (_number * _multi);
}
function add(_number, _add){
return (_number + _add);
}
function subtract(_number, _sub){
return (_number - _sub);
}
// #########################################################
var result = [aNumber()]
.map(item => divideBy(item, 2))
.map(item => add(item, 5))
.map(item => multiplyBy(item, 3))
.map(item => subtract(item, 10))
[0];
console.log(result);
This probably is not the most efficient way but usually speed is "good enough".
I'm creating a JavaScript library. I've been trying to implement chaining.
0: What I first came up with:
function V(p) {
return {
add : function(addend) { return V(p + addend); },
sub : function(subtra) { return V(p - subtra); },
};
}
Using this method I can chain easily:
V(3).add(7).sub(5) // V(5)
Unfortunately the result is always a wrapped V() function, I am unable to extract the resulting value this way. So I thought about this problem a bit and came up with two semi-solutions.
1: Passing flag to last method
function V(p, flag) {
if(flag)
return p;
else
return {
add : function(addend, flag) { return V(p + addend, flag); },
sub : function(subtra, flag) { return V(p - subtra, flag); }
};
}
Using this method I can end the chain by passing a flag to the last method I use:
V(3).add(7).sub(5, true) // 5
While this works just fine, it requires some code repetition and makes chaining less readable and my code less elegant.
2: Using start() and end() methods
_chain = false;
function V(p) {
function Wrap(w) {
return (_chain) ? V(w) : w;
}
return {
add : function(addend) { return Wrap(p + addend); },
sub : function(subtra) { return Wrap(p - subtra); },
start : function() { _chain = true; },
end : function() { _chain = false; return p; }
};
}
Using this method you can do single operations with no more code:
V(3).add(7) // 10
But chaining requires two more methods, making things a lot less readable:
V(3).start().add(7).sub(5).end() // 5
So basically I'm just searching for the best way to implement chaining into my library. Ideally I'm looking for something where I can use any number of methods and don't need to terminate the chain in inelegant ways.
V(3).add(7).sub(5) // 5, perfect chaining
Why not introducing a private variable and work on that? I guess that is even more convenient. Plus it's probably a good idea to have a pure "getter" that finally returns the computed value. This could look like this:
function V(p) {
var value = p;
return {
add: function(addend) {
value += addend;
return this;
},
sub: function(subtra) {
value -= subtra;
return this;
},
get: function() {
return value;
}
};
}
console.log(V(3).add(7).sub(5).get()); // 5
You cannot return the Object in a getter function obviously. So you need some method where the chaining ends and returns a value.
In some cases it does need to have something similar to end, but in your simple arithmetic example, it does not.
function V(initial_val){
if(!(this instanceof V)){
return new V(initial_val);
}
var num = initial_val || 0;
this.set = function(val){
num = val;
return this;
}
this.add = function(val){
num += val;
return this;
}
this.sub = function(val){
num -= val;
return this;
}
this.valueOf = function(){
return num;
}
this.toString = function(){
return ""+num;
}
}
By adding valueOf and toString functions to the object, you can access its primitive value. That is, you can do something like:
var num = V(0).add(1).sub(2), another_num = 3 + num; // num = -1 and another_num = 2;
I would amend Haochi's excellent answer as follows :
Using the prototype will be more efficient if you have many V objects and
in the toString function I invoke the generic number toString with whatever
arguments you care to give it.
function V (n) {
if (!(this instanceof V)) {
return new V (n);
}
this.num = +n || 0;
return this;
}
V.prototype = {
set: function (val) {
this.num = val;
return this;
},
add: function (val) {
this.num += val;
return this;
},
sub: function (val) {
this.num -= val;
return this;
},
valueOf: function () {
return this.num;
},
toString: function () {
return this.num.toString.apply (this.num, arguments);
}
}
I found this code in my website sourcecode:
var _0xd28d=["\x5F\x30\x78\x33\x32\x6C\x73\x6A\x39","\x5F\x78\x6C\x74","\x5F\x78\x38\x66\x6B\x63\x33","\x66\x6C\x6F\x6F\x72","\x72\x61\x6E\x64\x6F\x6D","\x6C\x65\x6E\x67\x74\x68"];
var _0x9ae4=[_0xd28d[0],12,_0xd28d[1],_0xd28d[2],2,31,Math,_0xd28d[3]];
var _0xcd6e=[_0x9ae4[5],_0x9ae4[0],_0x9ae4[_0x9ae4[4]],_0x9ae4[3],4,_0xd28d[4]];
var _0xr6g0={};
_0xr6g0[_0xcd6e[2]]=0;
_0xr6g0[_0x9ae4[4]]=function (){
var _0x4c68x4={};
_0x4c68x4[_0xd28d[0]]=_0x9ae4[0];
do{
_0x4c68x4[_0x9ae4[0]]+=_0x4c68x4[_0xd28d[0]][_0x9ae4[6][_0x9ae4[7]](_0x9ae4[6][_0xcd6e[5]]()*_0x4c68x4[_0xd28d[0]][_0xd28d[5]])];
}while(_0x4c68x4[_0xd28d[0]][_0xd28d[5]]<_0xcd6e[0]);
_0x4c68x4[_0x4c68x4[_0x9ae4[0]]]=function (){
_0xr6g0[_0xcd6e[2]]++;
_0xr6g0[_0xcd6e[2]]%=_0x9ae4[1];
return _0x4c68x4[_0x4c68x4[_0x9ae4[0]]];
};
return _0x4c68x4[_0x4c68x4[_0xcd6e[1]]];
};
_0xr6g0[_0x9ae4[_0xcd6e[4]]]()()()()()()()()()()()()()()()();
I was wondering, what is it? And What does it does?
By itself, the code does nothing useful nor dangerous.
After manually deobfuscating:
count = 0;
func_a = function() {
func_b = function() {
count++;
count %= 12;
return func_b;
};
return func_b;
};
func_a()()()()()()()()()()()()()()()();
Looks like more an invalid attempt to keep the browser busy. But very valid to keep people curious.
UPDATE: fixed the deobfuscation.
The first 5 lines initialize variables. After decrypting the \x escapes and indexing to other arrays, we get:
_0xd28d = ['_0x32lsj9', '_xlt', '_x8fkc3', 'floor', 'random', 'length']
_0x9ae4 = ['_0x32lsj9', 12, '_xlt', '_x8fkc3', 2, 31, Math, 'floor']
_0xcd6e = [31, '_0x32lsj9', '_xlt', '_x8fkc3', 4, 'random']
_0xr6g0 = {'_xlt': 0}
Lines 6-18 create a function (after expanding the array indexing):
_0xr6g0[2] = function() {
var _0x4c68x4={};
_0x4c68x4['_0x32lsj9'] = '_0x32lsj9';
do{
_0x4c68x4['_0x32lsj9']+=_0x4c68x4['_0x32lsj9'][Math['floor'](Math['random']()*_0x4c68x4['_0x32lsj9']['length'])];
} while(_0x4c68x4['_0x32lsj9']['length'] < 31);
_0x4c68x4[_0x4c68x4['_0x32lsj9']] = function (){
_0xr6g0['_xlt']++;
_0xr6g0['_xlt'] %= 12;
return _0x4c68x4[_0x4c68x4['_0x32lsj9']];
};
return _0x4c68x4[_0x4c68x4['_0x32lsj9']];
};
Javascript allows a['b'] as an alternate syntax for a.b, so this is equivalent to:
_0xr6g0[2] = function() {
var _0x4c68x4 = {'_0x32lsj9': '_0x32lsj9'};
do{
_0x4c68x4._0x32lsj9 += _0x4c68x4._0x32lsj9[Math.floor(Math.random()*_0x4c68x4._0x32lsj9.length)];
} while(_0x4c68x4._0x32lsj9.length < 31);
_0x4c68x4[_0x4c68x4._0x32lsj9] = function (){
_0xr6g0._xlt++;
_0xr6g0._xlt %= 12;
return _0x4c68x4[_0x4c68x4._0x32lsj9];
};
return _0x4c68x4[_0x4c68x4._0x32lsj9];
};
The inner function has a randomly-generated 31-character name that doesn't matter, so it can be simplified to:
_0xr6g0[2] = function() {
function f()
{
_0xr6g0._xlt++;
_0xr6g0._xlt %= 12;
return f;
};
return f;
};
The last line calls _0xr6g0[2] 16 times, and this is an obfuscated way of writing
_0xr6g0._xlt = 4
The hex in this code is creating a string with the text "_0x32lsj9_xlt_x8fkc3floorrandomlength"
The rest is parsing that to run some sort of javascript.