使用coffeescript递归检查数组中的随机元素
Recursively check random element in array using coffeescript
我有一个用咖啡脚本开发的代码库,因此正在努力学习它。给定一个对象数组,我如何从数组中随机 select 一个对象,检查它是否 is_available
属性 是 true 并且 return 它是 name
属性,否则从数组中移除对象并再次递归调用函数?
这就是我在 JavaScript 中的做法。我不确定如何将其转换为 coffeescript:
var collection = [
{name: 'Ford', is_available: true, color: 'blue'},
{name: 'Toyota', is_available: false, color: 'green'},
{name: 'Honda', is_available: false, color: 'red'}
];
var findItem = function(arr, prop) {
var position = Math.floor(Math.random() * arr.length);
var item = arr[position];
if (arr.length === 0) {
console.log(arr.length, 'Array is empty. Ending!');
return;
}
else if (item[prop] === true) {
console.log('Found one!',item.name);
return item.name;
}
else if (item[prop] === false) {
arr.splice(position, 1); //Remove item from the array
console.log(arr);
return findItem(arr, prop); //Recursively call function again.
}
};
findItem(collection, 'is_available');
如果用户要求获得一个随机元素,使谓词成立,Array::filter
可能更好 -
filterItem = (arr, prop) ->
filteredColl = arr.filter (elem) -> elem[prop]
filteredColl[Math.floor(Math.random()*filteredColl.length)].name
我有一个用咖啡脚本开发的代码库,因此正在努力学习它。给定一个对象数组,我如何从数组中随机 select 一个对象,检查它是否 is_available
属性 是 true 并且 return 它是 name
属性,否则从数组中移除对象并再次递归调用函数?
这就是我在 JavaScript 中的做法。我不确定如何将其转换为 coffeescript:
var collection = [
{name: 'Ford', is_available: true, color: 'blue'},
{name: 'Toyota', is_available: false, color: 'green'},
{name: 'Honda', is_available: false, color: 'red'}
];
var findItem = function(arr, prop) {
var position = Math.floor(Math.random() * arr.length);
var item = arr[position];
if (arr.length === 0) {
console.log(arr.length, 'Array is empty. Ending!');
return;
}
else if (item[prop] === true) {
console.log('Found one!',item.name);
return item.name;
}
else if (item[prop] === false) {
arr.splice(position, 1); //Remove item from the array
console.log(arr);
return findItem(arr, prop); //Recursively call function again.
}
};
findItem(collection, 'is_available');
如果用户要求获得一个随机元素,使谓词成立,Array::filter
可能更好 -
filterItem = (arr, prop) ->
filteredColl = arr.filter (elem) -> elem[prop]
filteredColl[Math.floor(Math.random()*filteredColl.length)].name