RamdaJS lib curry syntax breakdown - javascript

I'm not sure what this or arguments applies to in curry function, since arguments binds to hosting function, in which case that is "a" which I don't belief actually gets used anywhere.
var _isPlaceholder = require('./_isPlaceholder');
/**
* Optimized internal one-arity curry function.
*
* #private
* #category Function
* #param {Function} fn The function to curry.
* #return {Function} The curried function.
*/
module.exports = function _curry1(fn) {
return function f1(a) {
if (arguments.length === 0 || _isPlaceholder(a)) {
return f1;
} else {
return fn.apply(this, arguments);
}
};
};
var _curry1 = require('./internal/_curry1');
/**
* Creates a new object from a list key-value pairs. If a key appears in
* multiple pairs, the rightmost pair is included in the object.
*
* #func
* #memberOf R
* #since v0.3.0
* #category List
* #sig [[k,v]] -> {k: v}
* #param {Array} pairs An array of two-element arrays that will be the keys and values of the output object.
* #return {Object} The object made by pairing up `keys` and `values`.
* #see R.toPairs, R.pair
* #example
*
* R.fromPairs([['a', 1], ['b', 2], ['c', 3]]); //=> {a: 1, b: 2, c: 3}
*/
module.exports = _curry1(function fromPairs(pairs) {
var result = {};
var idx = 0;
while (idx < pairs.length) {
result[pairs[idx][0]] = pairs[idx][1];
idx += 1;
}
return result;
});

The use of arguments here simply allows more than one argument to be applied to the function, while ensuring at least one non-placeholder argument is provided.
The binding of this just ensures that the underlying function is called with the same this that the curried functions is evaluated with.

Related

merge two sorted link-list JS

Merge Two Sorted Lists
You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists in a one sorted list. The list should be made by
splicing together the nodes of the first two lists.
Return the head of the merged linked list.
https://leetcode.com/problems/merge-two-sorted-lists/description/
I am trying to solve this problem and i don't understand why my logic or code is wrong !!
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* #param {ListNode} list1
* #param {ListNode} list2
* #return {ListNode}
*/
var mergeTwoLists = function(list1, list2) {
let head = new ListNode()
let temp = head
while(list1 && list2){
if(list1.val>list2.val){
head.next = list2
list2 = list2.next
}
if(list1.val <= list2.val){
head.next = list1
list1 = list1.next
}
head = head.next
}
if(list1){
head.next = list1
}
if(list2){
head.next = list2
}
return temp.next
};
My test case is this:
Thank you

Map.filter() not returning expected output

I'm trying the leetcode remove elements problem. The goal is to remove all the elements from an array equal to a certain value. For example if the array = [3, 2, 2, 3] and the val = 3 the output array should be [2, 2].
My filter function seems to be producing the correct output based on the console log, but in the return statement it is something totally different.
Below is a copy of my code:
/**
* #param {number[]} nums
* #param {number} val
* #return {number}
*/
var removeElement = function(nums, val) {
let filteredNums = nums.filter(element => {
return element !== val
});
console.log(filteredNums)
return filteredNums;
};
Here is what I am getting for the output:
Is there something I am doing incorrect that I am missing?
By assuming to remove elements form the array, you could use a different approach by splicing the array.
By using Array#splice, you need to iterate from the end of the array, because the index is changing for deleted elements.
Finally you need to return the new length of the array.
/**
* #param {number[]} nums
* #param {number} val
* #return {number}
*/
var removeElement = function(nums, val) {
let i = nums.length;
while (i--) if (nums[i] === val) nums.splice(i, 1);
return nums.length;
};
var array = [3, 2, 2, 3];
console.log(removeElement(array, 3));
console.log(array);
Nina's answer is very good;
We can also solve the problem without using built-in functions – especially for easy LeetCode questions that's somewhat important (for interviews, not the contests):
const removeElement = function(nums, val) {
let lo = 0;
let hi = nums.length - 1;
while (lo <= hi) {
if (nums[lo] === val) {
swap(nums, lo, hi);
hi -= 1;
} else {
lo += 1;
}
}
return lo;
};
const swap = function(nums, left, right) {
const temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
return nums;
};
// console.log(removeElement(nums = [3,2,2,3], val = 3));
Disclaimer:
Don't know JavaScript well;
Well, it works as intended:
const removeElement = function(nums, val) {
let filteredNums = nums.filter(element => {
return element !== val
});
console.log("From inside of the function:", filteredNums)
return filteredNums;
};
const exampleArray = [3, 2, 2, 3];
const element = 3;
console.log("Original array before:", exampleArray)
const result = removeElement(exampleArray, element);
console.log("Returning array:", result);
console.log("Original array after:", exampleArray)
One thing that may trip you up is the fact that filteredNums is not changing the incoming array, instead it returns a copy of the original array without filtered out elements.

Call native functions from inherited system array

I created a new class called OrderedArray which extends a system Array:
export class OrderedArray<T> extends Array<T> {
/* istanbul ignore next */
constructor(elements: T[], private _comparer: (a: T, b: T) => number) {
super(...elements);
Object.setPrototypeOf(this, OrderedArray.prototype);
this.sort(this._comparer);
}
/**
* Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.
* #override
*/
public thenBy(keySelector: (key: T) => any): OrderedArray<T> {
return new OrderedArray(
this,
composeComparers(this._comparer, keyComparer(keySelector, false))
);
}
/**
* Performs a subsequent ordering of the elements in a sequence in descending order, according to a key.
* #override
*/
public thenByDescending(keySelector: (key: T) => any): OrderedArray<T> {
return new OrderedArray(
this,
composeComparers(this._comparer, keyComparer(keySelector, true))
);
}
/**
* Converts the OrderedList back to an array to be able to chain other actions to.
*/
public toArray(): T[] {
let returnArray = new Array();
returnArray.addRange(this);
return returnArray;
}
}
Which transpiles down to ES5:
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var OrderedArray = /** #class */ (function (_super) {
__extends(OrderedArray, _super);
/* istanbul ignore next */
function OrderedArray(elements, _comparer) {
var _this = _super.apply(this, elements) || this;
_this._comparer = _comparer;
Object.setPrototypeOf(_this, OrderedArray.prototype);
_this.sort(_this._comparer);
return _this;
}
/**
* Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.
* #override
*/
OrderedArray.prototype.thenBy = function (keySelector) {
return new OrderedArray(this, composeComparers(this._comparer, keyComparer(keySelector, false)));
};
/**
* Performs a subsequent ordering of the elements in a sequence in descending order, according to a key.
* #override
*/
OrderedArray.prototype.thenByDescending = function (keySelector) {
return new OrderedArray(this, composeComparers(this._comparer, keyComparer(keySelector, true)));
};
/**
* Converts the OrderedList back to an array to be able to chain other actions to.
*/
OrderedArray.prototype.toArray = function () {
var returnArray = new Array();
returnArray.addRange(this);
return returnArray;
};
return OrderedArray;
}(Array));
This allow me to do: array.orderBy(m => m.field).thenBy(m => m.field2);
This will return an OrderedArray object, which in the console looks like:
Which looks like an array, even prototypes as such, but when calling native array functions like slice, the following error occurs:
Uncaught TypeError: CreateListFromArrayLike called on non-object
Now I have to call toArray() after the last orderBy function call to convert it to a proper array, but is this necessary? Is there a way to call native array functions on my object?

Can I reuse a function inside the same function? [duplicate]

This question already has answers here:
Getting a random value from a JavaScript array
(28 answers)
Closed 7 years ago.
var items = Array(523, 3452, 334, 31, ..., 5346);
How do I get random item from items?
var item = items[Math.floor(Math.random()*items.length)];
1. solution: define Array prototype
Array.prototype.random = function () {
return this[Math.floor((Math.random()*this.length))];
}
that will work on inline arrays
[2,3,5].random()
and of course predefined arrays
var list = [2,3,5]
list.random()
2. solution: define custom function that accepts list and returns element
function get_random (list) {
return list[Math.floor((Math.random()*list.length))];
}
get_random([2,3,5])
Use underscore (or loDash :)):
var randomArray = [
'#cc0000','#00cc00', '#0000cc'
];
// use _.sample
var randomElement = _.sample(randomArray);
// manually use _.random
var randomElement = randomArray[_.random(randomArray.length-1)];
Or to shuffle an entire array:
// use underscore's shuffle function
var firstRandomElement = _.shuffle(randomArray)[0];
If you really must use jQuery to solve this problem (NB: you shouldn't):
(function($) {
$.rand = function(arg) {
if ($.isArray(arg)) {
return arg[$.rand(arg.length)];
} else if (typeof arg === "number") {
return Math.floor(Math.random() * arg);
} else {
return 4; // chosen by fair dice roll
}
};
})(jQuery);
var items = [523, 3452, 334, 31, ..., 5346];
var item = jQuery.rand(items);
This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value!
For extra fun, the array return is generated by calling the function recursively based on the array's length :)
Working demo at http://jsfiddle.net/2eyQX/
Here's yet another way:
function rand(items) {
// "~~" for a closest "int"
return items[~~(items.length * Math.random())];
}
Or as recommended below by #1248177:
function rand(items) {
// "|" for a kinda "int div"
return items[items.length * Math.random() | 0];
}
var random = items[Math.floor(Math.random()*items.length)]
jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,
var randomItem = items[Math.floor(Math.random()*items.length)]
// 1. Random shuffle items
items.sort(function() {return 0.5 - Math.random()})
// 2. Get first item
var item = items[0]
Shorter:
var item = items.sort(function() {return 0.5 - Math.random()})[0];
Even shoter (by José dB.):
let item = items.sort(() => 0.5 - Math.random())[0];
var rndval=items[Math.floor(Math.random()*items.length)];
var items = Array(523,3452,334,31,...5346);
function rand(min, max) {
var offset = min;
var range = (max - min) + 1;
var randomNumber = Math.floor( Math.random() * range) + offset;
return randomNumber;
}
randomNumber = rand(0, items.length - 1);
randomItem = items[randomNumber];
credit:
Javascript Function: Random Number Generator
If you are using node.js, you can use unique-random-array. It simply picks something random from an array.
An alternate way would be to add a method to the Array prototype:
Array.prototype.random = function (length) {
return this[Math.floor((Math.random()*length))];
}
var teams = ['patriots', 'colts', 'jets', 'texans', 'ravens', 'broncos']
var chosen_team = teams.random(teams.length)
alert(chosen_team)
const ArrayRandomModule = {
// get random item from array
random: function (array) {
return array[Math.random() * array.length | 0];
},
// [mutate]: extract from given array a random item
pick: function (array, i) {
return array.splice(i >= 0 ? i : Math.random() * array.length | 0, 1)[0];
},
// [mutate]: shuffle the given array
shuffle: function (array) {
for (var i = array.length; i > 0; --i)
array.push(array.splice(Math.random() * i | 0, 1)[0]);
return array;
}
}

Retrieving all values from a JavaScript object

This is the function I wrote to retrieve all the values in an given object.
function getValues(data){
var keys = Object.keys(data);
var values = [];
for(var i = 0, l = keys.length, key; i< l; i++){
key = keys[i];
values.push(data[key]);
}
return values;
}
Is there any builtin way to retrieve all the values in an object? Something like this exists in java for HashMaps. I know JS has a method for retrieving all the keys by doing Object.keys(obj).
Probably the most concise way of getting an array of the values contained within an object is to use Object.keys and Array.prototype.map:
obj = {
a: 1,
b: 2,
c: 3
};
values = Object.keys(obj).map(function (key) {
return obj[key];
});
Otherwise there's no standardized way of getting an array of an object's values.
For iterating, ES6 introduces a for..of loop which will iterate through an object's values:
continued from above:
for (value of obj) {
console.log(value); //1, 2, 3
}
ES7 is slated to introduce array comprehensions, so generating the values array could be written as:
continued from above:
values = [for (x of Object.keys(obj)) obj[x]];
If you're already using underscore, you can use the _.values method:
continued from above:
_.values(obj); //[1, 2, 3]
If you just want an efficient implementation for this utility function, the lodash source is:
lodash.js v2.4.1 lines 2891-2914
/**
* Creates an array composed of the own enumerable property values of `object`.
*
* #static
* #memberOf _
* #category Objects
* #param {Object} object The object to inspect.
* #returns {Array} Returns an array of property values.
* #example
*
* _.values({ 'one': 1, 'two': 2, 'three': 3 });
* // => [1, 2, 3] (property order is not guaranteed across environments)
*/
function values(object) {
var index = -1,
props = keys(object),
length = props.length,
result = Array(length);
while (++index < length) {
result[index] = object[props[index]];
}
return result;
}
You could do this, in newer Browsers:
Object.defineProperty(Object.prototype, 'values', {
get:function(){
return function(o){
var a = [];
for(var i in o){
a.push(o[i]);
}
return a;
}
}
});
var arrayOfValues = Object.values({a:'A',b:'B',c:'C'});
Really, I would just do:
function objectValues(obj, inherited){
var a = [];
for(var i in obj){
var v = obj[i];
if(inherited){
a.push(v);
}
else if(obj.hasOwnProperty(i)){
a.push(v);
}
}
return a;
}
var notInheritedArrayOfValues = objectValues({a:'A',b:'B',c:'C'});
var inheritedArrayOfValues = objectValues({a:'A',b:'B',c:'C'}, true);

Categories

Resources